Twitter API Local Trend Parsing - stdClass Error
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 开发者_Go百科$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?
@Ken: Try
$obj = json_decode($result, true);
if (is_array($obj)) {
foreach ($obj[0]->trends as $trend) {
echo "<li class=\"atlanta\">" . $trend->name . "</li>";
}
} else {
// failure case here
}
精彩评论