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

1.1k views Asked by At

How do you decode the tweets.json string returned from a twitter search API request? I have looked through answers to similar questions. Those answers do show how to make a call, and how to display the data returned, but those don't deal with the issue of dealing with the structure of the data that is returned from the tweets.json API call. Here's the code - it uses the twitter API. It requests search results.

<?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 />";
}
?>

If I was using a twitter API timeline call, I could use json_decode and access $items['text'] for each of the returned tweets But I want to use the twitter API search call (tweets.json). json_decode does not properly decode the data from this search call, it only returns two empty $items['text']

So what's the best way to decode the tweets.json string returned from a twitter API request?

2

There are 2 answers

5
Almazik G On

You need to iterate through the $items array and get the text property off of there.

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

After examining the data I noticed that is consisted of two JSON encoded strings, named statuses and search_metadata. I extracted the statuses string and was able to decode it using json_decode.