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
If you already have the string loaded to a variable, you can pass it to
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:
Once it’s loaded by SimpleXML you can reference the
awesome node by calling the
awesome variable on the SimpleXML object:
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;
To access the third
child inside of the
children node, you would call:
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 :)