Refine Post By:

Read XML Using PHP

Want to learn how to read XML using PHP? XML is used to store and transport data in an organized structure. With that said, XML can be used to create data sets and you can also use XML to create configuration files/settings for frameworks. To truly understand how PHP XML Parsing works, you should probably be familiar with PHP objects. Additionally, If you are unfamiliar with XML, check out this article XML Introduction.

PHP SimpleXML Overview

PHP5 comes with a number of integrated XML libraries. The one we’re going to be using is SimpleXML. SimpleXML is used to easily read and parse XML files. You can use SimpleXML to write and alter data sets but there are other XML libraries that are far more superior to accomplish these tasks.

The XML Structure

Let’s start off with an XML data set and than we’ll take a look at how to parse it. I created a simple data set of music songs and saved it as “songdata.xml”. Each song has a title and author. Take a look:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<music>
	<song>
		<author>Third Eye Blind</author>
		<title>Jumper</title>
	</song>
	<song>
		<author>Oasis</author>
		<title>Wonderwall</title>
	</song>
	<song>
		<author>The Used</author>
		<title>Taste of Ink</title>
	</song>
</music>

Make sense? Again, if you don’t understand XML, check out the article XML Introduction.

Loading the XML file with PHP

Now that we got our XML data set, we’re going to use the PHP SimpleXML library to load the file and instantiate our object with the simplexml_load_file() method. Within your PHP file, include the following code:

1
2
$xml_file = "songdata.xml";
$xml_object = simplexml_load_file($xml_file);

Easy enough? You can use print_r on the $xml_object to see the structure of our new SimpleXML object if you’d like.

Using PHP to return the values of the Object

Now that we got our XML file loaded as a PHP object, let’s iterate through it and return our data. We will use the SimpleXML children() method to grab the “child nodes” (<song>) of or XML “parent node” (<music>) in combination with a foreach loop to iterate through the object and return the values of the nodes (<author>) and (<title>). It will look something like this:

1
2
3
4
5
6
foreach($xml_object->children() as $song) {
	$song_author = $song->author;
	$song_title = $song->title;
 
	print $song_author . " - " . $song_title . " <br />";
}

Congratulations, you just parsed your XML data set and returned the information within! If you’d like to learn more about parsing XML with SimpleXML, there’s a more in depth tutorial called Parsing XML using SimpleXML. Hope this helped! Enjoy.

No Comments

Leave a comment