2011-07-31 53 views
3

我試圖用PHP解碼Google Dictionary API的JSON響應,但我遇到了一個問題,我似乎無法解析響應(json_decode返回NULL)。谷歌字典API的json_decode

示例JSON響應位於here(搜索單詞「oracle」)。

JSON API要求您提交一個回調函數,所以我選擇了一些很短的東西(a),因爲它沒有必要處理。

這裏是我的代碼:

<?php 
$query = 'oracle'; 
$file = file_get_contents('http://www.google.com/dictionary/json?callback=a&q='.$query.'&sl=en&tl=en&restrict=pr,de&client=te'); 
var_dump($file); 
$json = json_decode($file); 
var_dump($json); 
?> 

回答

5

谷歌返回結果的函數調用的形式。如果你想擺脫,你可以這樣做: 所以你必須去除該部分關閉:

$file = substr($file, 2, -10); 

此外,所有的十六進制字符會導致混亂。我不知道處理這些問題的最佳方法(他們應該轉換爲他們的角色,但如何去解決這個問題很容易就需要考慮)。出於測試目的,您可以將它們剝離(以查看它然後工作)。 嘗試:

$file = preg_replace("/\\\x[0-9a-f]{2}/", "", $file); 

所以,你到底有:

<?php 
$query = 'oracle'; 
$file = file_get_contents('http://www.google.com/dictionary/json?callback=a&q='.$query.'&sl=en&tl=en&restrict=pr,de&client=te'); 
// var_dump($file); 
$file = substr($file, 2, -10); 
$file = preg_replace("/\\\x[0-9a-f]{2}/", "", $file); 
echo $file; 
$json = json_decode($file); 
var_dump($json); 
?> 

轉換用的字符根據需要,我想你可以使用preg_replace_callback,但我不喜歡這樣的功能,特別是當數據來自遠程來源。簡單的可能是簡單地有一個靜態映射,例如:

$from = array("\x3d", "\x22", ...); 
$to = array("=", "\"", ...); 
$file = str_replace($from, $to, $file);