我正在尝试使用 PHP 解码 Google Dictionary API JSON 响应,但我遇到了似乎无法解析响应的问题(json_decode
返回 NULL
).
示例 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);
?>
最佳答案
Google 以函数调用的形式返回结果。如果你想摆脱它,你可以这样做: 所以你必须去掉那部分:
$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);
关于php - Google Dictionary API 的 json_decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889764/