WARNING: The below code is deprecated as of June 11, 2013. I’ve created a snippet that’s updated here: Twitter Feed With PHP and JSON using API v1.1
Note: the API has a limit of 150 pings per hour, so be careful out there. I’ll have a snippet soon on caching tweets.
<?php
$userid = 'johnbhartley'; //your handle
$count = '5';
$responseJson = file_get_contents('http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$userid.'&include_rts=1&count='.$count);
if ($responseJson) {
$response = json_decode($responseJson);
}
echo '<ul>';
foreach ($response as $tweet) {
$tweet_text = $tweet->text; //get the tweet
// make links link to URL
$tweet_text = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href='\2'>\2</a>", $tweet_text);
// make hashtags link to a search for that hashtag
$tweet_text = preg_replace("/#([a-z_0-9]+)/i", "<a href="http://twitter.com/search/$1">$0</a>", $tweet_text);
// make mention link to actual twitter page of that person
$tweet_text = preg_replace("/@([a-z_0-9]+)/i", "<a href="http://twitter.com/$1">$0</a>", $tweet_text);
// display each tweet in a list item
echo "<li>" . $tweet_text . "</li>n";
}
echo '</ul>';
?>
This snippet will help you add your twitter status to any site with PHP and the Twitter JSON file. It is output into a list and the number of tweets is controlled by the variable $count. Be sure to switch out my name for your twitter handle, unless you want to show all of my tweets, which would be weird.
This is just a quick fix to what I had previously used, which was the XML file, which as of yesterday, no longer seemed to work. Happy status-showing and as always, let me know if you’ve found a better way to pull this off.
Note: More explanation to come laters.
The post Twitter Status With PHP and Twitter JSON (snippet) appeared first on John B. Hartley.