PHP - How to read and parse an XML file
Article Metadata
This article explains how to read and parse XML data in PHP.
Contents |
Introduction
This article shows how you can easily use the PHP to parse XML formatted data, read it into PHP variables and display out. Additionally you could write the parsed data to another file, database...the choise is yours.
Prerequisites
- A code/text editor of your choise.
- PHP 5.x installed and accessible (localhost or remote).
- A web browser
Example code
In this example we will have two files: an example XML file and a PHP file that contains the required code for reading and parsing out the XML file.
XML file
XML file
<bands>
<band>
<name>Helloween</name>
<albums>18</albums>
</band>
<band>
<name>Metallica</name>
<albums>18</albums>
</band>
<band>
<name>Judas Priest</name>
<albums>18</albums>
</band>
<band>
<name>Iron Maiden</name>
<albums>18</albums>
</band>
</bands>
PHP file
In the PHP script we will read the XML file node by node into an array. The file variable is $filename. The simplexml_load_file() function has been with PHP since version 5.0. It enables the reading and opening an XML file and accessing it's structure.
<?php
$filename = simplexml_load_file('test.xml');
echo $filename->band[1]->name.' '.$filename->band[1]->albums;
?>
The above code will display the second band name, a space, and the number of albums the band has (remember that the zero [0]is the first item in the array).
To go thru all of the bands and display the albums for all the bands, we would need to use a loop as follows:
<?php
$filename = simplexml_load_file('test.xml');
foreach ($filename->band as $band) {
echo $band->name.' '.$producer->albums.'<br'>;
}
?>
Summary
You can use this method to process any XML feed or file to separate out the elements in it.


(no comments yet)