PHP Twitter Hashtag Search在解析中没有显示结果,但在数组中显示数据

时间:2013-08-04 00:09:43

标签: php json search twitter hashtag

<?php
require_once('TwitterAPIExchange.php');


/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "HIDDEN FOR STACK ASSIST",
    'oauth_access_token_secret' => "HIDDEN FOR STACK ASSIST",
    'consumer_key' => "HIDDEN FOR STACK ASSIST",
    'consumer_secret' => "HIDDEN FOR STACK ASSIST"
);
// Your specific requirements
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=#trekconspringfield&result_type=recent';



$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                   ->performRequest();

$response = json_decode($response, true); //tried with and without true - throws class error without it.

foreach($response as $tweet)
{
   $url = $tweet['entities']['urls'];
    $hashtag = $tweet['entities']['hashtags'];
    $text = $tweet['text'];

    echo "$url <br />";
    echo "$hashtag <br />";
    echo "$text <br />";
    echo "<br /><br />";

}
echo "<pre>". var_dump($response) ."</pre>";
?>

当我运行此代码时,它会在响应中获取数据,但是当我尝试解析它以将数据分成有用的东西时,它显示为空白。我已经在这里完成了几乎所有PHP JSON和Twitter标签的答案,并尝试了几乎所有这些都没有成功。发送给守则上帝的答案。谢谢。

目前上传到的网页... http://trekconspringfield.com/twitter.php

2 个答案:

答案 0 :(得分:2)

$response包含两个条目:statusessearch_metadata。你可能想要遍历statuses,所以你应该像这样循环:

foreach($response['statuses'] as $tweet)
{
    $text = $tweet['text'];
}

您将面对此代码的下一个问题是$url$hashtag - 它们是数组,因此您不能只是echo它们,您必须迭代并仅收集相关信息回声。

还有一件事:

echo "<pre>". var_dump($response) ."</pre>";

var_dump不会返回任何内容,因此无法与<pre>连接。要具有可读输出,请使用它:

echo "<pre>";
echo var_dump($response);
echo "</pre>";

答案 1 :(得分:0)

如果查看$response,您会看到以错误的方式访问它。

我查看了一些数据,它的格式如下:

array(

    "statuses" => array(
        array(
            // some stuff
            "text" => "#trekconspringfield Springfield is the place to be now and on May 9th 2014!",
            "user" => array( /* some stuff */ )
        ),

        array(
            // some stuff
            "text" => "#trekconspringfield rocks",
            "user" => array( /* some stuff */ )
        ),

        array(
            // some stuff
            "text" => "#trekconspringfield",
            "user" => array( /* some stuff */ )
        ),
    )

);

要获得精确的结构,数组索引等,您必须使用print_r()进行检查,因为var_dump()会在输出中添加太多无用的垃圾。