Home arrow PHP arrow Page 4 - Introducing SimpleXML in PHP 5

Creating a basic XML parsing class - PHP

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.

  1. Introducing SimpleXML in PHP 5
  2. Reading XML files with the “simplexml_load_file()” function
  3. Accessing file nodes as array elements
  4. Creating a basic XML parsing class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 51
June 12, 2006

print this article



In order to parse XML files using an object-oriented approach, in this section I’ll build a simple PHP 5 class. It will use the “simplexml_load_function()” that you learned before as the workhorse for reading and processing XML data. This class will take, as a unique parameter, the name of the XML file that will be parsed, and its definition is as follows:

class XMLParser{
    private $xml;
    public function __construct($xmlFile='default_xml_file.xml'){
            throw new Exception('Invalid XML file.');
        // read XML file
            throw new Exception('Error reading XML file.');
    // fetch specific nodes according to node name
    public function fetchNodes($nodeName){
            throw new Exception('Invalid node name.');
        foreach($this->xml as $node){
        return $nodes;
    // fetch all nodes as array of objects
    public function fetchNodesAsObjects(){
        foreach($this->xml as $node){
        return $nodes;
    // count nodes of type $nodeName
    public function countNodes($nodeName){
            throw new Exception('Invalid node name.');
        foreach($this->xml as $node){
        return $nodeCounter;

If you take a close look at the “XMLParser” class that I listed above, you’ll see that the logic it implements is pretty straightforward. As I said before, the constructor first accepts as an argument the name of the XML file to be parsed, and then verifies whether this file is valid. Once the contents of this file have been loaded by the “simplexml_load_file()” function, they’re assigned to the $this->xml class member.

The remaining methods exposed by the class speak for themselves, so I’ll provide a brief explanation of what they do. That said, the “fetchNodes()” method is tasked with returning an array containing all the nodes that match a given name, while the “fetchAllNodes()” method is responsible for returning all the nodes contained in the given XML file. Regarding this last method, the complete set of nodes will be returned as an array of objects to be processed from outside the class.

Finally, the “countNodes()” method, as its name suggests, returns the number of nodes within the XML file that match a specific name, which can be quite useful if you want to find out how many nodes of a particular type are contained inside an XML file.

Now that you have a clear idea of the tasks performed by each method, take a look at the following script, which shows you precisely how to use them:

    // instantiate new 'XMLParser' object
    $xmlPar=new XMLParser('users.xml');
    // fetch <name> nodes
    // display <name> nodes
    foreach($nameNodes as $name){
        echo 'Name. '.$name.'<br />';
    // fetch nodes as array of objects
    // display nodes
    foreach($nodes as $node){
        echo 'Postal address: '.$node->address.'<br />';
    // display number of nodes
    echo 'Found '.$xmlPar->countNodes('address').' address
catch(Exception $e){
    echo $e->getMessage();

The previous example shows how to utilize the “XMLParser” class, in conjunction with the “users.xml” XML file that I created before. The script calls the “fetchNodes()” method, in order to retrieve all the <name> nodes, which are then displayed by a “foreach” loop.

Next, the “fetchAllNodes()” method is invoked, which comes in handy for returning all the file nodes as an array of objects. Finally, the script displays the number of <address> nodes included within the sample XML file. To complete the example, here’s the output generated by the prior script:

Name. John Doe
Name. Janet Smith
Name. James Smith
Name. Silvia Wilson
Name. Alejandro Gervasio
Postal address: Binary Avenue 1234 FL
Postal address: Crazy Bits Road 4568 CA
Postal address: Socket Boulevard 7894 OH
Postal address: Protocol Avenue 5652 NY
Postal address: Boulevard of Objects 10101 AR
Found 5 address nodes

As you can see, using the “XMLParser” class is a snap, since the “simplexml” extension is remarkably capable of simplifying the parsing of basic XML files. As I expressed right at the beginning of this article, if your application is going to parse simple XML files, this extension might fit your needs perfectly.

Final thoughts

In this first article of the series, I explained the basics of using the “simplexml” extension that comes with PHP 5. As you saw by the different examples, this library is primarily focused on parsing simple XML files, and certainly exposes a good package of functions for doing a decent job.

Since in this tutorial I used only the “simplexml_load_file()” function, in the next one I’ll show you how to utilize other handy functions included in the library, which are useful for searching and replacing nodes. However, you’ll have to wait for the next part. See you there!

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: