Pull tweets via php, update via JQuery/Ajax
I currently have a script that pulls tweets (on a search topic e.g. 'awesome') from twitter, and displays them. The script displays the latest 20 tweets.
I want to develop my script further. I would like to check to see if any new tweets have been tweeted after the page has loaded, if so then show them, whilst still only showing 20 per page (so they all move down).
Here is currently what I have so far:
<?php
function get_file($uri) {
return file_get_contents($uri);
};
$xml = get_file('http://search.twitter.com/search.atom?q=awesome%20-rt&lang=en&rpp=20');
$tweets = new simpleXMLElement($xml);
?>
<div id="entries">
<?php
foreach ($tweets->entry as $tweet) {
echo '<div class="entry">';
echo '<img class="tweet-pic" src="'.$tweet->link[1]->attributes()->h开发者_如何学Cref.'" />';
echo '<p class="tweet">'.$tweet->title.'</p>';
echo '<p class="tweep"><a class="link" href="'.$tweet->link[0]->attributes()->href.'">'.$tweet->author->name.'</a></p>';
echo '<div class="clear"></div>';
echo '</div>';
echo '<hr/>';
}
?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" language="javascript"></script>
<script>
$(document).ready(function(){
getlatest();
});
function getlatest() {
$.ajax({
type: "GET",
url: "index.php",
cache: false,
success: function(html){
$("div#entries").prepend(html);
$(".entry").slideDown("1000");
}
});
setTimeout("getlatest();",10000);
}
</script>
Any help would be much appreciated.
Well, when you get the XML each tweet has a timestamp associated. From here, in your AJAX call (which you could run every X time with setTimeout, you can compare the first tweet in your list and the first from the XML.
If it's date is more recent, you should:
- Look for the next tweet after your first one. I mean, the first from the XML doesn't have to be the unique new into the call.
- Get all the new tweets, starting from the one that you have just found.
- Replace the HTML with the new one from the tweets.
精彩评论