从Twitter API使用时出现未定义的索引错误

时间:2011-08-17 04:39:49

标签: php curl twitter

我正在尝试使用cURL和PHP从Twitter API中提取每日趋势,但我收到Undefined index错误。我做错了什么?

这是我的PHP代码

<?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
    } 
?>

显示错误:

Notice: Undefined index: query in C:\xampp\htdocs\twitter_trends\index.php on line 22

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

2 个答案:

答案 0 :(得分:0)

使用名称/查询从数组中删除两个级别。

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

print_r($response)如果你感到困惑。

答案 1 :(得分:0)

您需要像这样更改foreach部分:

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
        }
    } 

?>