Rui Rui - 4 months ago 12
JSON Question

Receive JSON response while POST urlencoded

I want to receive and decode JSON response after submitting urlencoded request by POST.

But all I got ($content) after running below is garbled characters.

I believe the server returns correct values (I checked via hurl.it)

PHP code is below.

$target_url = "http://examples.com/send";]
$headers = array(
'Host: examples.com',
'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
'Accept-Language: en-us',
'Accept-Encoding: gzip, deflate',
'User-Agent: Appcelerator Titanium/3.5.0',
);
$data = array(
'id' => 'hogehoge',
'command' => 'renew'
);

$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($data),
'header' => implode("\r\n", $headers),
));

$contents = file_get_contents($target_url, false, stream_context_create($options));
echo $contents;


Headers of response is

Connection: keep-alive
Content-Encoding: gzip
Content-Length: 32
Content-Type: application/json; charset=utf-8
Date: ***** GMT
Server: Apache
Vary: Accept-Encoding,User-Agent


When I echo $contents, I got

�ォV*J-.ヘ)Qイ2ャワゥp0


although it should be

{"result":1}


Thanks in advance.

ADD:
When I
var_dump(json_decode($contents))
,I got
NULL

Answer

In response, server is informing you that it is sending zipped content, you must unzip it.

Content-encoding: gzip

You can use gzdecode() to unzip gzip.

echo gzdecode($content);