从Twitter Search API解析JSON响应无法使用PHP

时间:2013-09-23 21:36:39

标签: php json parsing twitter

我正在使用Twitter Search API 1.1搜索特定关键字的推文,并将结果显示为motherpipe.co.uk上的搜索结果页。

我设法在http://github.com/j7mbo/twitter-api-php的James Mallison的帮助下让Oauth工作。

我陷入了从Twitter获得的实际响应的阶段,并且通常以HTML格式显示在div中(使用PHP)。这是我收到的回复:https://motherpipe.co.uk/staging/index2.php

我似乎无法编写一个简单的循环来仅显示'screen_name'和'text'。

到目前为止,我尝试了不同的版本:

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=sweden&result_type=recent';


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


$response = json_decode($twitter);

foreach($response as $tweet)
{
  echo "{$tweet->screen_name} {$tweet->text}\n";
}

非常感谢任何有关如何正确循环的反馈或想法。

干杯

4 个答案:

答案 0 :(得分:1)

如果您执行var_dump $response,您可能会更好地了解结构。看起来你需要循环$response->statuses。用户信息位于$tweet->user->screen_name下,推文文字位于$tweet->text下。所以:

$response = json_decode($twitter);

foreach($response->statuses as $tweet)
{
  echo "{$tweet->user->screen_name} {$tweet->text}\n";
}

答案 1 :(得分:1)

用户信息位于$tweet->user->screen_name下,推文文字位于$tweet->text

$response = json_decode($twitter);

foreach($response->statuses as $tweet)
{
  echo "{$tweet->user->screen_name} {$tweet->text}<br />";
}

或者你也可以使用它

$response = json_decode($twitter, true);
$counter = 0;
foreach($response['statuses'] as $tweet)
{
  echo "{$tweet[$counter]['user']['screen_name'] {$tweet[$counter]['text']}<br />";
  $counter +=1;
}

答案 2 :(得分:1)

所以答案(感谢Prisoner,Jonathan Kuhn和Mubin Khalid)是为了显示来自Twitter Search API的响应,为Twitter JSON响应分配一个变量。这将使您能够循环并显示您想要的响应。

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$requestMethod = 'GET';
$getfield = '?q=sweden&result_type=recent';


$twitter = new TwitterAPIExchange($settings);

$api_response = $twitter ->setGetfield($getfield)
                     ->buildOauth($url, $requestMethod)
                     ->performRequest();


$response = json_decode($api_response);

foreach($response->statuses as $tweet)
{
  echo "{$tweet->user->screen_name} {$tweet->text}\n";
}

答案 3 :(得分:1)

我不使用詹姆斯代码,但我让它以其他方式工作

<ul>
<?php $get_tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

foreach($get_tweets as $tweet) { 

$tweet_desc = $tweet->text;
?>

<li><?php echo $tweet_desc ?></li>

<?php }?>
</ul>

你可以在this page.的页脚看到正在运行的Twitter Api V1.1。如果你想要这样的东西或进一步定制,请告诉我。