Home arrow PHP arrow Page 4 - Loading XML Strings with simpleXML in PHP 5

Parsing XML strings by an object-oriented approach: building a PHP 5 XML parsing class - PHP

Are you looking forward to learning about loading XML data strings, as well as searching and accessing nodes? Then this is the tutorial you’ve been waiting for since last week! Welcome to the second part of the series “Working with simpleXML in PHP 5.” This three-part series introduces the most important features of the “simpleXML” extension that comes with PHP 5, and shows by several hands-on examples how to implement the handy set of XML-parsing functions that are included in this library.

TABLE OF CONTENTS:
  1. Loading XML Strings with simpleXML in PHP 5
  2. Parsing basic XML strings: using the "simplexml_load_string()" function
  3. More examples with the "simplexml_load_string()" function: accessing parent and child nodes
  4. Parsing XML strings by an object-oriented approach: building a PHP 5 XML parsing class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 9
June 19, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- 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: