Parsing the attributes of XML elements

PHP 5.0 contains some excellent functions for parsing XML into arrays and objects, but that isn’t much good to you if you have to used PHP 4.0.

That said, it is relatively straightforward to extract the data from between XML tags in PHP 4.0, but the particular problem I came across was having to extract attribute values from the tags themselves. This arose in relation to exchange rate data published by the ECB, which you can view here:

http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

As you can see, the data we really want (the exchange rate and currency name) is an attribute value rather than raw data between the tags.

Anyway, to get at this data you need to look at the $attrs associative array that is passed to whatever ‘start element’ function you are using. This will work (CUBE is the tagname we want in the ECB feed):

function startElement($parser, $name, $attrs) {
global $insidecube, $tag;

if ($insidecube) {
$tag = $name;
} elseif ($name == “CUBE”) {
foreach ( $attrs as $name => $value ) {
echo $name . ” ” . $value . “\n”;
}
$insidecube = true;
}

}

This just prints the attribute keys and values on your screen, but you get the idea.