2017-07-07 80 views
0

我正在写一个客户端的API ...如何在PHP中使用Zend Json Json :: decode(...)解码unicode编码的JSON?

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 

如何得到一个Unicode编码的JSON解码的Zend\Json


编辑

只是通知,该JSON坏了。它分为两部分。字符串以1f9e开头,然后是第一部分,然后是字符串\u043,然后是第二个内容部分,然后是0

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

确定的JSON是有效的? –

+0

我也用邮差测试过它。所以,是的,我认为,我可以肯定,这是有效的。但编码。 – automatix

+0

等一下,也许你是对的。只需将Postman的“漂亮”视图的API调用输出放到'Json :: decode(...)'作品中即可。然后我从“原始”视图输入相同的输出。我预计它不会工作。但实际上它也起作用。所以,它真的好像是我从'Zend \ Http \ Response#getContent()'得到的JSON的一个问题。 – automatix

回答

1

使用Zend\Json\Decoder ZF2的组成部分。它有一个称为Decoder::decodeUnicodeString()的静态方法,它解码unicode字符。请致电here

希望这会帮助你!

+0

谢谢你的回答! +1但其实问题在于我的情况在破碎的JSON中。请参阅[此问题](https://stackoverflow.com/q/44978260/2019043)以获取更多信息。 – automatix

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; 

结果是:

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

谢谢你的回答,但是请在我的问题中看到**编辑**并且[这个问题](https://stackoverflow.com/q/44978260/2019043),因为 - 你是对的 - JSON本身是可以的,但它在开头和结尾都带有一些附加符号。这些附加字符串之间的JSON实际上是有效的。但是,所有这些都会产生无效的JSON字符串。 – automatix