0

I have the following code, in which I am getting Tweets in JSON format on an HTML page, I want this to be displayed neatly on an HTML page. I have included the foreach loop, however I am getting the following error: " json_decode() expects parameter 1 to be string, array given ".

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) 
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

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

$resArr = json_decode($tweets, 1); // decodes the json string to an array

if (is_array($resArr))
{
    foreach ($resArr as $tweet)
    {
        echo $tweet['text']."<br />";
    }
}

I have also tried using the following code, after reading other suggestions, however an error "Using $this when not in object context":

$resArr = json_decode($this->item->extra_fields, true); 

Would anyone please provide me with some guidance?

user2675041
  • 115
  • 1
  • 5
  • 15

2 Answers2

1

Your error "json_decode() expects parameter 1 to be string, array given" hints that $tweets is already an array (not a string). Try the following:

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

foreach ($tweets as $tweet)
{
    echo $tweet->text."<br />";
}
datchung
  • 3,778
  • 1
  • 28
  • 29
0

Since I have switched from using arrays to using objects I had to alter the PHP code as follows.

foreach ($tweets as $tweet)
{
    echo $tweet->text;
    echo "<br />\n";
}

This answer explains it best, https://stackoverflow.com/a/16589380/2675041

Community
  • 1
  • 1
user2675041
  • 115
  • 1
  • 5
  • 15