Skip to content

Blog

Twitter web integration

Author: Justin Munro

We have decided to add more integration with services like Twitter on our new website. This will make the site content more dynamic and hopefully interesting to users as various parts of the website will regularly change. As you may have noticed our new website has twitter integration on the home page. This simply adds just the latest tweet from our twitter account to the What's New section.

After researching various methods to achieve this l discovered it was actually quite easy. Twitter gives you a XML feed which is the first thing you will need to obtain using the following code:

$aTweets = file_get_contents("http://twitter.com/statuses/user_timeline/blmuk.xml?count=1");

The variable $aTweets now contains the XML file contents. You can change the 'count' variable in the URL to be the number of tweets you wish the XML to contain.

Next you need to create a new DOM instance and then load the XML into it (http://php.net/manual/en/book.dom.php):

$aXMLDoc = new DOMDocument();
$aXMLDoc->loadXML($aTweets);

Now you have loaded the XML you can use the DOM to access the various elements of the Twitter XML. Below is an example of printing just the contents of the tweets:

$aStatusUpdates = $aXMLDoc->getElementsByTagName("status");

foreach($aStatusUpdates as $aNode)
{
$aStatusUpdate = $aNode->getElementsByTagName("text");
print $aStatusUpdate->item(0)->nodeValue;
}