[英]Parsing JSON / associative arrays in from Twitter API response in PHP
[英]Parsing JSON response from Twitter Search API not working using PHP
我正在使用Twitter Search API 1.1搜索特定關鍵字的推文,並將結果顯示為motherpipe.co.uk的搜索結果頁面。
我已經設法讓James Mallison在http://github.com/j7mbo/twitter-api-php的幫助下完成了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";
}
任何有關如何正確循環的反饋或想法將非常感激。
干杯
如果你要做一個$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 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";
}
我不使用詹姆斯代碼,但我讓它以其他方式工作
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.