开发者

Undefined index error when using from Twitter API

I'm trying to pull the daily trends off the Twitter API using cURL and PHP but I get Undefined index errors. What am I doing incorrectly?

Here's my php code

<?php
$trends_url = "http://api.twitter.com/1/trends/daily.json";

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $trends_url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$curlout = curl_exec($ch);

curl_close($ch);

$response = json_decode($curlout, true);

foreach($response as $trend){

$url = $trend['query'];

$name = $trend['name'];

?>

<div class="trend">
    <a href="http://www.twitter.com/<?php echo $url;?>"><?php echo $name;?></a>
</div
<?php
    } 
?>

shows the error:

Notice: Undefined index: query in C:\xamp开发者_高级运维p\htdocs\twitter_trends\index.php on line 22

Notice: Undefined index: name in C:\xampp\htdocs\twitter_trends\index.php on line 24


You're two levels off from the arrays with the names/queries.

foreach($response as $array){
    foreach ($array as $date) {
        foreach ($date as $trend) {
            echo $trend['query'] . "\n";
        }
    }
}

print_r($response) if you're confused.


You need to change the foreach portion like this:

foreach($response['trends'] as $trend){

    foreach($trend as $trend)
    {
        $url = $trend['query'];

        $name = $trend['name'];

        ?>
        <div class="trend">
            <a href="http://www.twitter.com/<?php echo $url;?>"><?php echo $name;?></a>
        </div>
        <?php
        }
    } 

?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜