To get my last tweet in PHP I use this code :
function getTweets($tweetsToDisplay, $user_id) {
$twitterrequest = 'http://api.twitter.com/1/statuses/user_timeline.json?user_id=' . $user_id . '&include_rts=true&count=' . $tweetsToDisplay;
$twitterci = curl_init($twitterrequest);
curl_setopt($twitterci, CURLOPT_RETURNTRANSFER, TRUE);
$twitterinput = curl_exec($twitterci);
curl_close($twitterci);
return ($twitterinput);
}
$user_id = '99999999';
$var = json_decode(getTweets(1, $user_id));
$txt = $var[0]->text;
$txt = preg_replace('%(https?://)[^\s]*%', '$1...', $txt);
echo $txt;
Works fine but I want to get the date as well. How to extract it ?
I hope code below help you.
function getTimeline($count, $username) {
$url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&count=.'$count;
$tweets = json_decode(file_get_contents($url),TRUE);
return $tweets;
}
You can try this simple PHP function that I created to catch latest tweets easily (does not require API authentication). Must be optimized :)
function getTweets($user, $count) {
$datas = file_get_contents('https://twitter.com/'.$user);
preg_match_all('/<p class="js-tweet-text tweet-text">(.*?)<\/p>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<s>(.?)<\/s>/', '$1', $matchetweets[1]);
$matchetweets[1] = preg_replace('/(class|dir|rel|data-expanded-url|data-pre-embedded|data-query-source)="(.*?)"/', '', $matchetweets[1]);
$matchetweets[1] = preg_replace('!\s+!', ' ', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
Usage
echo getTweets('nasa', 3);
UPDATE (10/15/2014) :
This version is out of date and not working anymore. Here is an updated PHP code to parse tweets easily.
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
UPDATE (5/30/2015) :
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/s', $datas, $matchetweets, PREG_SET_ORDER);
for ($i = 1; $i <= $count; $i++) {
$matchetweets[$i][0] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[$i][0]);
$matchetweets[$i][0] = preg_replace('/\s+/', ' ', $matchetweets[$i][0]);
$matchetweets[$i][0] = str_replace('"> ', '">', $matchetweets[$i][0]);
echo '<li>'.$matchetweets[$i][0].'</li>'."\n";
}
};
Usage doesn't change. Minimum 1 tweet, maximum 20 tweets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With