How To Parse XML With PHP : Get The Atrributes

In my first post about XML I showed you how to parse an xml file without attributes, in this post we are going to use the same xml file we used last time, which we named “xml-file.xml”

<?xml version="1.0" encoding="UTF-8"?>
<library>
	<book>
		<title>PHP and MySQL</title>
		<author>Miguel Alvarez</author>
		<publisher>WebHole</publisher>
		<price>1.99</price>
	</book>
	<book>
		<title>JAVA 123</title>
		<author>WIlliam Vega</author>
		<publisher>WebHole</publisher>
		<price>2.99</price>
	</book>
</library>

But this time we are going to add attributes to the tags <book> and <author> so our new XML file will look like this now.

<?xml version="1.0" encoding="UTF-8"?>
<library>
	<book isbn10="1234567890" isbn13="1234567890123">
		<title>PHP and MySQL</title>
		<author fname="miguel" lname="alvarez">Miguel Alvarez</author>
		<publisher>WebHole</publisher>
		<price>1.99</price>
	</book>
	<book isbn10="8957468873" isbn13="0984837828189">
		<title>JAVA 123</title>
		<author fname="william" lname="vega">WIlliam Vega</author>
		<publisher>WebHole</publisher>
		<price>2.99</price>
	</book>
</library>

Notice I added the attributes “isbn10” and “isbn13” to the <book> tags and <fname> (first name) and <lname> (last name) to the <author> tags. So, our goal will be to get these values from the file.

Now let’s fill in the basics of our “parser.php” file, which are, the url of the file we want to parse, in this case “xml-file.xml”, and the function we used “simplexml_load_file()”. Your parser.php file should look like this then.

<?php
$url = "xml->file.xml";
$xml = simplexml_load_file($url);

Now that the file is loaded into the variable $xml we can get started. Remember that “$xml->book[0]” refers to the first <book> tag from top to bottom, so “$xml->book[1]” refers to the second <book> tag. So to get the isbn13 of the second book tag you would do the following.

// assign value of attribute "isbn13" of the second book to variable $isbn13
$isbn13=$xml->book[1]["isbn13"];

As you can see this is the same as a two dimensional array. Now we are going to get the author’s “fname” attribute of the first book.

// assign value of attribute "fname" of the first book to variable $author
$author=$xml->book[0]->author["fname"];

In short, we can say that if you want to get a tag’s attribute, simply put the name of the tag “tagName” followed by the attribute inside brackets and quotes (single or double) , so the syntax is ” tagName[“NameOfAttribute” ]” and this should get the value of that attribute.

That’s all I have to say for this tutorial, I’ll show you how to loop through several results in part 3 kind of like you do when you fetch results from a database, this will be the final post on “Parsing XML With PHP”, thanks for reading and tell me what you think in the comments below.