如何使用Zend \ Json \ Json :: decode(...)解码PHP中的unicode编码JSON?

时间:2017-07-07 18:43:15

标签: php json unicode zend-framework2

我正在为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();

...并获得这样的unicode编码JSON:

...{"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"...

首先,我尝试使用json_decode(...)对其进行解码。但我没有找到任何适当的方法在PHP中执行此操作(没有可疑的基于正则表达式的方法)。

现在我正在尝试使用Zend\Json\Json::decode(...)并收到以下错误:

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

如何获取使用Zend\Json解码的unicode编码的JSON?

修改

请注意,JSON已损坏。它分为两部分。该字符串以1f9e开头,然后是第一部分,然后是字符串\u043,然后是第二个内容部分,然后是0

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

2 个答案:

答案 0 :(得分:1)

使用ZF2的Zend\Json\Decoder组件。它有一个名为Decoder::decodeUnicodeString()的静态方法,用于解码unicode字符。

请查看脚本here

希望这会对你有帮助!

答案 1 :(得分:0)

一旦我看到这个json似乎没有被打破。请考虑下一个代码行:

$data = '{"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"}';

$json = json_decode($data);

header('Content-Type: text/html; charset=utf-8');
echo $json->title;
echo "<br/>";
echo $json->short_name;

结果是:

иллюстрации
ИЛЛЮСТРАЦИИ