1

我正在使用 wordpress 函数 wp_remote_get 从 twitter 获取 json 数据,如下所示:

$response = wp_remote_get('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter');
$json = json_decode($response['body']);

它工作正常。但是,如果 twitter 返回一些错误,它完全会在我的页面上产生问题。在这种情况下,我页面上的内容在该错误部分之后不会加载。那么,只有在没有错误的情况下,我才能捕获错误并继续。

例如,如果 twitter 限制超出,它会返回以下响应:

{"request":"\/1\/statuses\/user_timeline.json?screen_name=twitter","error":"Rate limit exceeded. Clients may not make more than 150 requests per hour."}

从上面的响应中,我怎么能得到错误。我正在尝试关注,但它不起作用(我的页面根本没有加载)

if (!isset($json['error']){
    //continue
}
4

2 回答 2

6

它不起作用,因为您试图$json作为数组访问,但事实并非如此。这是一个对象,所以使用:

if (!isset($json->error){
    //continue
}

您的页面无法加载,因为它会导致致命错误,进而产生 500 内部服务器错误。如果您检查错误日志,您会发现:

致命错误:不能在 .... 中使用 stdClass 类型的对象作为数组

于 2012-11-27T08:05:06.927 回答
1

您需要使用 json_decode 在对象中“转换”您的“json 字符串”。

$j = json_decode($json);
echo $j->{'error'}

在这里你会找到你需要知道的关于 json_decode 的一切:http: //php.net/manual/en/function.json-decode.php

于 2012-11-27T08:11:18.077 回答