解析来自 Twitter 搜索 API 的 JSON 响应无法使用 PHP 工作


Parsing JSON response from Twitter Search API not working using PHP

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

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

被困在获取我从Twitter获得的实际响应并将其正常显示在HTML(使用PHP)中的div中的阶段。这是我得到的答复:https://motherpipe.co.uk/staging/index2.php。

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

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

$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";
}

有关如何正确循环的任何反馈或想法将不胜感激。

干杯

我不使用 james 代码,但我让它以另一种方式工作

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

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

如果你对$response做一个var_dump,你可能会对结构有更好的了解。看起来你需要循环$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";
}

用户信息在$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;
}

所以答案(感谢Prisoner,Jonathan Kuhn和Mubin Khalid)是,为了显示来自Twitter搜索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";
}