PHP
  Home arrow PHP arrow Page 4 - Introducing SimpleXML in PHP 5
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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: 5 stars5 stars5 stars5 stars5 stars / 32
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In the course of this first article, you'll learn how to use some of the most...
       · I enjoyed your article. All the xml files you used were stored on the server, is...
       · Hello JET:I'm happy to know you enjoyed my article. Thank you. Now, in response...
       · Nice article, I only found an mistake during the countNodes function.The $nodeName...
       · I'm glad to know that the article has been useful to you. Now, with reference to...
       · Hi,this solution doesn't work for me.if I remove an 'address' element from...
       · Hello Bob,Thank you for your comments. I tested the method and works just fine....
       · Hi,thank you for your answer.Tested it again and still get the same output...
       · Hi Bob,Thank you for your feedback. Okay, there was a small bug on the method....
       · Hi,thank you for your answer.In the meantime I also found a working...
       · Hi Bob,I'm glad to see you found an alternative solution to the one I provided...
       · can you share how you removed an entire node?thxwalter
       · Thanks for the comments on my PHP article. Basically, to remove a node you might...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





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