How to decode a Unicode encoded JSON in PHP with Zend \ Json \ Json :: decode (& hellip;)?

advertisements

I'm writing a client for an API...

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();

... and get a unicode encoded JSON like this:

...{"id":"7","title":"\u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438","short_name":"\u0418\u041b\u041b\u042e\u0421\u0422\u0420\u0410\u0426\u0418\u0418"...

First I tried to decode it with json_decode(...). But I didn't find any appropriate method to do this in PHP (without suspect regex based approaches).

Now I'm trying it with Zend\Json\Json::decode(...) and getting following error:

/var/www/path/to/project/vendor/zendframework/zend-json/src/Json.php:243
Decoding failed: Syntax error

How to get a unicode-encoded JSON decoded with Zend\Json?


EDIT

Just notices, that the JSON is broken. It is separated to two parts. The string starts with 1f9e, then the first part, then the string \u043, then the second content part, then 0.

1f9e <-- What is it?
{"_li...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0


Use Zend\Json\Decoder component of ZF2. It has a static method called Decoder::decodeUnicodeString() which decodes unicode characters.

Please have a look at the script here.

Hope this would help you!