如何使用 Zend\Json\Json::d ecode(..)在 PHP 中解码 unicode 编码的 JSON



我正在为 API 编写一个客户端...

use ZendHttpClient;
use ZendHttpRequest;
use ZendJsonJson;
...
$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":"u0438u043bu043bu044eu0441u0442u0440u0430u0446u0438u0438","short_name":"u0418u041bu041bu042eu0421u0422u0420u0410u0426u0418u0418"...

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

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

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

如何获得使用ZendJson解码的Unicode编码的JSON?


编辑

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

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

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

请在此处查看脚本。

希望这对您有所帮助!

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

$data = '{"id":"7","title":"u0438u043bu043bu044eu0441u0442u0440u0430u0446u0438u0438","short_name":"u0418u041bu041bu042eu0421u0422u0420u0410u0426u0418u0418"}';
$json = json_decode($data);
header('Content-Type: text/html; charset=utf-8');
echo $json->title;
echo "<br/>";
echo $json->short_name;

结果是:

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

最新更新