Using PHP Guzzle HTTP 6 to send JSON with data that is already encoded

Tom Wright picture Tom Wright · Apr 18, 2016 · Viewed 13.9k times · Source

I am trying to send a POST request which contains a raw JSON string with the following header: Content-Type: application/json.

From looking at the docs, I can see that I can do something like this...

$data = ['x' => 1, 'y' => 2, 'z' => 3];
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'json' => $data,
];
$client->post('http://example.com', $options);

My problem is that when I get to this point, $data has already been json_encode'd.

I have tried the following but it does not work.

$data = json_encode(['x' => 1, 'y' => 2, 'z' => 3]);
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'body' => $data,
    'headers' => ['Content-Type' => 'application/json'],
];
$client->post('http://example.com', $options);

My question is: can I use the json option with an already-encoded array? Or is there a way for me to simply set the Content-Type header?

Answer

Dale picture Dale · Apr 18, 2016

According to guzzle's docs http://docs.guzzlephp.org/en/latest/request-options.html#json

You can pass the already encoded json directly into the body parameter

Note This request option does not support customizing the Content-Type header or any of the options from PHP's json_encode() function. If you need to customize these settings, then you must pass the JSON encoded data into the request yourself using the body request option and you must specify the correct Content-Type header using the headers request option.

This option cannot be used with body, form_params, or multipart