How to parse XML with PHP’s SimpleXML

Parsing XML in PHP couldn’t be easier thanks to the SimpleXML extension. SimpleXML allows you to read in an XML string, verify that it is in fact XML and can create an object that you can interact with by way of the node names in the XML.The SimpleXML extension also allows you to write out XML but for the sake of simplicity, I am only going to be covering reading / parsing XML in.

There are two ways to read in XML, calling a file directly or passing in an XML string. You can read in a file directory with simplexml_load_file:

$xml = simplexml_load_file('/path/to/your/xml/file.xml'

If you already have the string loaded to a variable, you can pass it to simplexml_load_string:

$xml = simplexml_load_string($xml_string

Now that we have the XML file or string loaded into SimpleXML we can interact with it. The $xml variable contains a SimpleXML object that you can reference by node name. Take for instance the following XML file:

<?xml version='1.0'?>
<root>
	<awesome>sauce</awesome>
</root>

Once it’s loaded by SimpleXML you can reference the awesome node by calling the awesome variable on the SimpleXML object:

$xml->awesome

Since “well-formed” XML always contains a single root node, it’s omitted from the object and you interface directory with whatever is in that node. In the case of nodes with multiple child nodes, you will need to interface with the object as well as with an array;

<?xml version='1.0'?>
<root>
	<children>
		<child>1</child>
		<child>2</child>
		<child>3</child>
	</children>
</root>

To access the third child inside of the children node, you would call:

$xml->children->child[2]

Even though it’s the third child, the array’s index still starts at 0.

That’s all there is to parsing XML in PHP. Next week we’ll discuss using SimpleXML to write out XML 🙂

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.