Simple Twitter API XML Parsing in PHP

A friend asked me the best way to parse XML in PHP. I didn’t have an answer. It doesn’t sound like a weird request but usually the XML parsing is done on the client side(AJAX/Flash/XSL) instead of the server side…..the one usually serving the XML.

Some quick googling led me to believe that this was very monotonous before PHP 5.

Here’s a quick and dirty script to easily traverse some XML.

$xml = simplexml_load_file(“http://twitter.com/statuses/user_timeline.xml?screen_name=shitmydadsays”);

//root
echo $xml->getName() . “
“;

foreach($xml->children() as $status)
{
//status
echo $status->getName() . “: ” . $status . “
“;
foreach($status->children() as $items)
{
echo $items->getName() . “: ” . $items . “
“;
//user
if($items->getName() == “user”){
foreach($items->children() as $user){
echo $user->getName() . “: ” . $user . “
“;
}

}
}
echo ‘———————–
‘;
}

Take this and drop it in a file or download this zip(right click save as) and run it in localhost or on your server.

2 thoughts on “Simple Twitter API XML Parsing in PHP

  1. I realize this is just an example – but for anyone who stumbles across this, I actually find that parsing Twitter data on the server is easier if you request json instead of XML (where available) and then parse with json_decode. The result is a plane-jane object and doesn’t require all the XML hoop through-jumping.

    Thanks for the example.

Leave a Comment

Your email address will not be published. Required fields are marked *

  Wordpress Theme Protected By Wp Spam Blocker