In the first article of a three-part series, you will learn the basics of using the “simplexml” extension that comes with PHP 5. This library is primarily focused on parsing simple XML files, and can save you a lot of work.
As I said before, after loading an XML file with the “simplexml_load_file()” function, it’s possible to access file nodes as array elements, which makes searching specific nodes a no-brainer task. In order to demonstrate this excellent functionality, I coded below a basic example that shows how to locate a specific node within the XML file I used before, and also displays additional data. Please take a look at this code listing:
// locates a specific node and displays name of first user if(!$xml=simplexml_load_file('users.xml')){ trigger_error('Error reading XML file',E_USER_ERROR); } // displays first user's name echo 'Displaying name of first user...<br />'; echo $xml->user[0]->name;
As illustrated above, once the contents of the sample “users.xml” XML file have been loaded, the script locates the first user and displays his full name:
Displaying name of first user... John Doe
As you can see, specific file nodes can be easily accessed by using a regular array syntax, as the line below demonstrates:
echo $xml->user[0]->name;
If you examine the above expression, you’ll understand how the first user is located (user[0]) and how that user's full name is properly displayed (user[0]->name). As you’ll probably realize, the “simpleXML” extension allows you to locate a given node easily within an XML file, as you would with regular arrays, and then access other sub nodes.
Based on the same “users.xml” XML file that you saw previously, here is the correct expression for accessing the last <user> node of the respective file and displaying its email address:
// locates a specific node and displays name of last user if(!$xml=simplexml_load_file('users.xml')){ trigger_error('Error reading XML file',E_USER_ERROR); } // displays last user's email address echo 'Displaying email address of last user...<br />'; echo $xml->user[4]->email;
Actually, the entire process for locating file nodes is reduced to navigating the three nodes, as illustrated in the previous example, so you shouldn’t have any problems accessing different nodes within a given XML file.
At this point, I’m pretty sure that you learned the basics of loading XML files and navigating across file nodes, since the “simpleXML” extension is very understandable. Considering this, in the next few lines I’ll build a simple PHP 5 class, which will behave as a simple wrapper for the “simplexml_load_file()” function, performing basic parsing of XML files. To find out how this will be achieved, please click on the link below and keep on reading.