簡體   English   中英

您如何解碼從Twitter搜索API請求返回的tweets.json字符串?

[英]How do you decode the tweets.json string returned from a twitter search API request?

您如何解碼從Twitter搜索API請求返回的tweets.json字符串? 我瀏覽了類似問題的答案。 這些答案的確顯示了如何進行調用以及如何顯示返回的數據,但是這些答案沒有涉及處理從tweets.json API調用返回的數據結構的問題。 這是代碼-它使用twitter API。 它要求搜索結果。

<?php
require_once('../TwitterAPIExchange.php');
$settings = array(
    'oauth_access_token' => "......",
    'oauth_access_token_secret' => "......",
    'consumer_key' => "......",
    'consumer_secret' => "......"
);

$requestMethod = 'GET';

//$url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; // I can decode output from this
//$getfield = "?screen_name=J7mbo&count=5"; // I can decode output from this
$url = "https://api.twitter.com/1.1/search/tweets.json"; // I can NOT decode output from this
$getfield = "?q=%23J7mbo&result_type=recent"; // I can NOT decode output from this

$twitter = new TwitterAPIExchange($settings);
$string = $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest(); // from stackOverflow
$string = json_decode($string, $assoc = TRUE); // seems i cannot use json_decode for output from tweets.json
if ($string["errors"][0]["message"] != "")
{
    echo "twitter error message:" . $string[errors][0]["message"];
    exit();
}
foreach ($string as $items)
{
    echo "tweet text =[". $items['text']."]<br />";
}
?>

如果我使用的是Twitter API時間軸調用,則可以使用json_decode並為每個返回的tweets訪問$items['text'] ,但我想使用twitter API搜索調用(tweets.json). json_decode (tweets.json). json_decode無法正確解碼此搜索調用中的數據,它僅返回兩個空的$items['text']

那么,解碼從Twitter API請求返回的tweets.json字符串的最佳方法是什么?

您需要遍歷$items數組並獲得text屬性。

    foreach ($items as $item) {
       echo "tweet text =[". $item['text']."]<br />";
    }

檢查數據后我發現是由兩個JSON編碼字符串,命名的statusessearch_metadata 我提取了statuses字符串,並能夠使用json_decode進行解碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM