Twitter API 本地趋势解析 - stdClass 错误
我正在尝试解析某个位置(本例中为亚特兰大)的最新 Twitter 趋势,
这是我的代码:
<html>
<head></head>
<body>
<?php
$init = 'http://api.twitter.com/1/trends/2357024.json?count=1&callback=?&exclude=hashtags';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$init);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
foreach ($obj[0]->trends as $trend) {
echo "<li class=\"atlanta\">".$trend->name."</li>";
}?>
</body>
</html>
所需的结果将是
它大约 30% 的时间有效 - 但其他 70% 我收到此错误:
Fatal error: Cannot use object of type stdClass as array in...
经过一番谷歌搜索后,似乎 obj 必须是数组...我找到的唯一答案是将 $obj 行更改为 true ,如下所示:
$obj = json_decode($result, true);
但是,这只会给我这个错误:
警告:为 foreach() 提供的参数无效...
有谁知道如何将我的代码更改为“数组”,以便它能够 100% 地工作?
I'm trying to parse the latest Twitter trend from a location (Atlanta in this case)
Here's my code:
<html>
<head></head>
<body>
<?php
$init = 'http://api.twitter.com/1/trends/2357024.json?count=1&callback=?&exclude=hashtags';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$init);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
foreach ($obj[0]->trends as $trend) {
echo "<li class=\"atlanta\">".$trend->name."</li>";
}?>
</body>
</html>
The desired result would be <li class="atlanta">Whatever The Trend Is</li>
It works about 30% of the time - but the other 70% I get this error:
Fatal error: Cannot use object of type stdClass as array in...
After some googling it seems the obj must be array... The only answer I've found is to change the $obj line to a true like this:
$obj = json_decode($result, true);
However, that simply gives me this error:
Warning: Invalid argument supplied for foreach() in...
Does anyone know how to change my code into an 'array' so that it will work 100% of the time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@肯:试试
@Ken: Try