Reputation: 4018
I have this code that creates an array of tweets based on the count value (currently set to 5) however, when I try to display the tweets I get nothing but the word Array repeated 5 times (and not the actual tweets), could anyone help me troubleshoot what I'm doing wrong?
By the way, if I change the count to 1 and just echo the variable $tweet, I get the latest tweet display correctly.
function get_tweet() {
require 'parts/tmhOAuth.php';
require 'parts/tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'taken out for security purposes',
'consumer_secret' => 'taken out for security purposes',
'user_token' => 'taken out for security purposes',
'user_secret' => 'taken out for security purposes',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'designernewsbot',
'count' => '5'));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
// This is to create links in my webpage if links are specified in the tweet
$tweet = $tweets[0]['text'];
$tweet = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweet);
$tweet = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $tweet);
$tweet = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $tweet);
foreach($tweets as $tweet):
echo $tweet;
endforeach;
}
Upvotes: 0
Views: 86
Reputation: 76666
The issue is in your foreach
loop. You're trying to print $echo
inside the loop, which is an array. So you'll receive an Array to string conversion
error.
A for
loop seems more suitable in this case:
for ($i=0; $i < count($tweets); $i++) {
echo $tweets[$i]['text']."\n";
}
Update:
To also show the links in tweets, you can do:
for ($i=0; $i < count($tweets); $i++) {
//echo $tweets[$i]['text']."\n";
$var = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/", "<a target=\"_blank\" href=\"$1\">$1</a>", $tweets[$i]['text']);
$var = preg_replace("/#([A-Za-z0-9\/\.]*)/", "<a target=\"_new\" href=\"http://twitter.com/search?q=$1\">#$1</a>", $var);
$var = preg_replace("/@([A-Za-z0-9\/\.]*)/", "<a href=\"http://www.twitter.com/$1\">@$1</a>", $var);
echo $var."\n";
}
I've tested this and it works. Hope this helps!
Upvotes: 1