1

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

pah
  • 4,700
  • 6
  • 28
  • 37
Rui
  • 27
  • 1
  • 1
  • 4

3 Answers3

0

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);
Muhammed
  • 1,592
  • 1
  • 10
  • 18
  • Just found this http://stackoverflow.com/questions/8895852/uncompress-gzip-compressed-http-response – Muhammed Mar 01 '16 at 19:15
0

unzip the content:

echo gzdecode($contents);
Tino Rüb
  • 799
  • 2
  • 13
  • 27
0

You are receiving a gziped string as pointed by the header Content-Encoding: gzip.

You can uncompress it using php or js.

http://php.net/manual/en/function.gzdecode.php

https://github.com/gcanu/gzip.js

incompleteness
  • 260
  • 1
  • 12