Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 23:46, 12 June 2014 by BuildNokia (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

PHP - How to read and parse an XML file

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (28 Jun 2012)
Last edited: BuildNokia (12 Jun 2014)

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.

This page was last modified on 12 June 2014, at 23:46.
234 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×