Google字典API的json_decode [英] json_decode for Google Dictionary API

查看:119
本文介绍了Google字典API的json_decode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP解码Google Dictionary API JSON响应,但是我遇到了一个似乎无法解析响应的问题(json_decode返回NULL).

I am trying to decode the Google Dictionary API JSON response with PHP, but I am running into an issue where I cannot seem to parse the response (json_decode returns NULL).

示例JSON响应位于

An example JSON response is located here (searching for the word "oracle").

JSON API要求您提交一个回调函数,因此我选择了一个非常简短的内容(a),因为它不需要处理.

The JSON API requires that you submit a callback function, so I chose something really short (a), since it's unnecessary to deal with.

这是我的代码:

<?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以函数调用的形式返回结果.如果您想摆脱它,可以执行以下操作: 因此,您必须去除该部分:

Google returns the result in the form of a function call. If you want to get rid of that you can do: So you have to strip that part off:

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

此外,所有十六进制字符都会造成混乱.我不知道处理这些问题的最佳方法(应该将它们转换为他们的性格,但是如何轻松地做到这一点需要思考).出于测试目的,您可以将它们剥离(以确保它可以正常工作). 试试:

Furthermore all the hex characters cause a mess. I don't know the best way of dealing with these (they should be converted to their character, but how to go about that easily requires thought). For testing purposes you can just strip them (to see that it then works). Try:

$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,但是我不喜欢该功能,特别是当数据来自远程源时.更简单的可能是简单地具有静态映射,例如:

For converting the characters as needed, I suppose you could use preg_replace_callback, but I don't like that function, specially when the data comes from a remote source. Simpler may be to simply have a static mapping, eg:

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

这篇关于Google字典API的json_decode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆