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

如何使用Zend\JSON\JSON::decode(…)在PHP中解码unicode编码的JSON?,php,json,unicode,zend-framework2,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'

我正在为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"...
首先,我试着用计算机解码。但如果没有基于regex的方法,我在PHP中找不到任何合适的方法来实现这一点

现在我正在尝试,并得到以下错误:

/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

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

请看一下剧本


希望这对你有帮助

一旦我看到这个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;

你确定JSON是有效的吗?我还用Postman对它进行了测试。所以,是的,我想,我可以肯定,它是有效的。但是,等等,也许你是对的。只需将API调用的输出从Postman的pretty视图放到Json::decode…-作品然后我从原始视图中输入相同的输出。我原以为它不起作用。但实际上它也起了作用。因此,我从Zend\Http\ResponsegetContent获得的JSON似乎确实存在问题。谢谢您的回答+1但事实上,问题在于我的JSON坏了。有关更多信息,请参阅。感谢您的回答,但请参阅我问题中的编辑,因为-您是对的-JSON本身是可以的,但它在开头和结尾都带有一些额外的符号。这些附加字符串之间的JSON实际上是有效的。但所有这些一起给出了一个无效的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;
иллюстрации
ИЛЛЮСТРАЦИИ