Tuesday, April 9, 2013

How to fetch Twitter latest updates using PHP?

many a times we need to fetch twitter updates on to our business website or elsewhere.
This is can very well achieved using the following lines of code.

<?php
$username='sachin_rt';
$format='xml';

$tweet=simplexml_load_file("https://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}");

echo $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\0\" target=\"_blank\">\0</a>", $tweet->status[0]->text);
?>
Source
Also if when we need to with our wordpress site

//Set parameter for query string
$username = 'sachin_rt';
$num = '10';
// Get the data from Twitter JSON API
$json = wp_remote_get("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$num");
// Decode JSON into array
$data = json_decode($json['body'], true);
//Create unordered list
echo '<ul class="twitter">';
//Loop through all twitter tweets and display the text with the time it was created
foreach($data as $tweets)
{
    $text = $tweets['text'];
    $date = $tweets['created_at'];
    //Make time human readable ie. 6 hours ago
    $h_time = sprintf( __('%s ago'), human_time_diff( $time ) );
    echo '<li>'.ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\0\" target=\"_blank\">\0</a>", $text) . ' '. $h_time . '</li>';
}
//Close list
echo '</ul>';

Share/Bookmark

No comments:

Post a Comment