开发者

PHP JSON Twitter Trends

开发者 https://www.devze.com 2023-02-06 07:40 出处:网络
Can anyone spot the problem with this PHP, nothing appears on the screen: <?php function get_data($url)

Can anyone spot the problem with this PHP, nothing appears on the screen:

<?php
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$url='http://search.twitter.com/trends.json';
$obj = json_decode(get_data($url));
foreach ($obj as $item) {
$trend = $item开发者_StackOverflow->name;
$link = $item->url;
echo "<a href='.$link.'>".$trend."</a>";
}
?>


You're not looping over the collection properly. Use:

foreach ($obj->trends as $item) {

Your $obj is an object (just a stdClass) with a trends property which is an array of objects with name and url properties. This reflects the structure of the JSON which looks like:

{
    "trends": [
        {
            "name": "#yepthatsme",
            "url": "http://search.twitter.com/search?q=%23yepthatsme"
        },
        {
            "name": "Miley Citrus",
            "url": "http://search.twitter.com/search?q=Miley+Citrus"
        },
        /* lots more */
        {
            "name": "Keith Olbermann",
            "url": "http://search.twitter.com/search?q=Keith+Olbermann"
        }
    ],
    "as_of": "Sat, 22 Jan 2011 13:37:25 +0000"
}
0

精彩评论

暂无评论...
验证码 换一张
取 消