0
<?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 标签答案,并尝试了几乎所有这些答案,但都没有成功。发送到 Code God's 寻求答案。谢谢你。

当前上传到的页面... http://trekconspringfield.com/twitter.php

4

2 回答 2

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>";
于 2013-08-04T00:28:47.490 回答
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()在输出中添加了太多无用的垃圾。

于 2013-08-04T00:27:44.273 回答