Wednesday, 19 August 2009

Parsing XML with PHP4

PHP is not something I'm familiar with, but I was recently helping out a friend and was surprised how difficult it was to find some sample code for downloading/parsing an XML (specifically using PHP4, apparently PHP5 has some built-in functionality).

Thankfully I stumbled across Taha Paksu's SimpleXML for PHP4 - you must join/login to download it, but it's worth it.

Once you have downloaded the ZIP file, place simplexml.class.php in your PHP 'app', and use the supplied example test.php to ensure everything is working:
<?
require_once "simplexml.class.php";

echo "<pre>";
$file = "http://musicbrainz.org/ws/1/track/?query=metallica&type=xml";
$sxml = new simplexml;
$data = $sxml->xml_load_file($file);
print_r($data);
?>
which prints out a 'tree view' of the XML data.

If that works, you can then address individual elements (say your XML looks like this - an example from the download)
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>
<format>text</format>
<content>Don't forget me this weekend!</content>
</body>
</note>
then your PHP might look like this:
<?
require_once "simplexml.class.php";

$file = "http://SOMESERVER.com/example.xml";
$sxml = new simplexml;
$data = $sxml->xml_load_file($file);
?>
<html>
<body>
<table>
<td>to:</td><td><?php echo $data->to; ?></td>
<td>sender:</td><td><?php echo $data->from; ?></td>
<td>subject:</td><td><?php echo $data->heading; ?></td>
<td>message:</td><td><?php echo $data->body->content; ?></td>
</table>
</body>
</html>


You can read more in the SimpleXML for PHP4 forum... That's enough PHP for now - back to c#/t-sql/xaml/html/javascript... and hopefully soon MonoTouch!

2 comments:

  1. Thanks mate! Took me a while to find this but worth the search!

    ReplyDelete
  2. Informative Blog

    Thanks for Sharing !!

    ReplyDelete