2017-07-07 78 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