Reputation: 14614
I have the following PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
foreach ($obj[0]->trends as $trend) echo utf8_decode($trend->name);
which works fine for URL #1 (into the variable $URL):
http://api.twitter.com/1/trends/1.json?exclude=hashtags
but causes an error "Cannot use object of type stdClass as array" for URL #2: http://api.twitter.com/1/trends/weekly.json?exclude=hashtags
I have searched for a while, but can't figure out a code to fix this and handle both URLs.
Any help would be much appreciated.
Upvotes: 0
Views: 726
Reputation: 724074
The first URL serves a JSON array as the root element. It contains an object, which in turn contains an array called trends
. You're correctly accessing it in your foreach
like so:
$obj[0]->trends
But the second URL serves a JSON object as the root element, which contains an object called trends
. Thus you can't use $obj[0]
to access what's in that root object. The object contains an array of trend names for each day of the week so you need to nest two foreach
loops to get to the trend info:
// Loop through each day of the week
foreach ($obj->trends as $date => $trends) {
// Get each trending topic for this day
foreach ($trends as $trend) {
echo utf8_decode($trend->name);
}
}
Upvotes: 1