PHP
  Home arrow PHP arrow Page 4 - Loading XML Strings with 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? 
Google.com  
PHP

Loading XML Strings with simpleXML in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 9
    2006-06-19


    Table of Contents:
  • Loading XML Strings with simpleXML in PHP 5
  • Parsing basic XML strings: using the "simplexml_load_string()" function
  • More examples with the "simplexml_load_string()" function: accessing parent and child nodes
  • Parsing XML strings by an object-oriented approach: building a PHP 5 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


    Loading XML Strings with simpleXML in PHP 5 - Parsing XML strings by an object-oriented approach: building a PHP 5 XML parsing class
    ( Page 4 of 4 )

    In order to show how simple XML data strings can be parsed via an object-based approach, here's the signature of a basic XML parsing class, which uses the "simplexml_load_string()" function for processing XML data. Take a look at the source code of this class:

    class XMLParser{
        private $xml;
        public function __construct($xmlString='default_xml_string'){
            if(!is_string($xmlString)){
                throw new Exception('Invalid XML string.');
            }
            // read XML string
            if(!$this->xml=simplexml_load_string($xmlString)){
                throw new Exception('Error reading XML string.');
            }
        }
        // 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 examine the above class, you'll see that it takes up an XML data string as the only input parameter, which is used inside the constructor for loading the XML string onto an object. Once this $xml object is available within the class, it's possible to retrieve all the XML nodes of the given string, through the "fetchNodesAsObjects()" method.

    Additionally, the class also has two extra methods. The first one, "fetchNodes()", is responsible for returning all the nodes that match a specific name, while the second one is tasked with counting the total number of specific nodes contained in the XML string.

    If you want to learn how all these methods are implemented, study the example below:

    try{
        // include XML string
        require_once 'xml_string.php';
        // instantiate new 'XMLParser' object
        $xmlPar=new XMLParser($xmlstr);
        // 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('email').' email nodes';
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    In this case, the above script first instantiates an "XMLParser" object, and next calls in sequence all the methods that I discussed previously. Notice how all the <name> nodes are retrieved by calling the "fetchNodes()" method, and how the number of <email> nodes is determined via the "countNodes()" method.

    Of course, the prior example wouldn't be complete if I don't show you its corresponding output:

    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 email nodes


    Whether you're using a procedural approach or an object-based method, parsing XML strings with the "simpleXML" library is a fairly comprehensive process that you can learn quickly and incorporate into your own PHP 5 applications.

    Final thoughts

    That's all for the moment. In this second tutorial, I showed you how to use the "simplexml_load_string()" function, in order to load and parse XML strings. Also, you learned how to access node attributes by using the syntax for associative array, which makes the whole learning experience even simpler and more straightforward.

    Over the course of the last installment of the series, I'll be covering some additional functions that are part of the "simpleXML" extension, useful for comparing and replacing XML nodes. See you in the last part!



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

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek