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?

2 Answers 2

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 />";
}
Sign up to request clarification or add additional context in comments.

2 Comments

I had tried that, however I got the following error: "Cannot use object of type stdClass as array"
Edited: Use -> instead of []
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.