PHP
  Home arrow PHP arrow Page 4 - Introducing SimpleXML in PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Introducing SimpleXML in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 37
    2006-06-12


    Table of Contents:
  • Introducing SimpleXML in PHP 5
  • Reading XML files with the “simplexml_load_file()” function
  • Accessing file nodes as array elements
  • Creating a basic XML parsing class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Introducing SimpleXML in PHP 5 - Creating a basic XML parsing class
    ( Page 4 of 4 )

    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'){
            if(!file_exists($xmlFile)){
                throw new Exception('Invalid XML file.');
            }
            // read XML file
            if(!$this->xml=simplexml_load_file($xmlFile)){
                throw new Exception('Error reading XML file.');
            }
        }
        // fetch specific nodes according to node name
        public function fetchNodes($nodeName){
            if(!$nodeName){
                throw new Exception('Invalid node name.');
            }
            $nodes=array();
            foreach($this->xml as $node){
                $nodes[]=$node->$nodeName;
            }
            return $nodes;
        }
        // fetch all nodes as array of objects
        public function fetchNodesAsObjects(){
            $nodes=array();
            foreach($this->xml as $node){
                $nodes[]=$node;
            }
            return $nodes;
        }
        // count nodes of type $nodeName
        public function countNodes($nodeName){
            if(!$nodeName){
                throw new Exception('Invalid node name.');
            }
            $nodeCounter=0;
            foreach($this->xml as $node){
                $nodeCounter++;
            }
            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:

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

    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
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT