PHP
  Home arrow PHP arrow Page 5 - Searching and Replacing Nodes 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? 
PHP

Searching and Replacing Nodes with SimpleXML in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 9
    2006-06-26


    Table of Contents:
  • Searching and Replacing Nodes with SimpleXML in PHP 5
  • Going deeper into parsing XML strings: comparing nodes
  • Finding nodes inside a XML string: using the “Xpath()” method
  • Replacing nodes within a XML string: using the “asXML()” method
  • Using a few additional methods: finding child nodes, accessing attributes and using the XML DOM

  • 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


    Searching and Replacing Nodes with SimpleXML in PHP 5 - Using a few additional methods: finding child nodes, accessing attributes and using the XML DOM
    ( Page 5 of 5 )

    As I said in the previous section, the “simpleXML” extension comes with some additional methods for parsing XML data, which can be quite useful, depending on the requirements of your PHP 5 applications.

    The first method that I’ll explain is called “children()”, and as its name suggests, is aimed at finding all the child nodes of a parent element. To clarify how it can be used, I’ll use the following XML data string:

    $xmlstr=<<<XML
    <?xml version="1.0" encoding="iso-8859-1"?>
    <users>
    <user>
    <name>John Doe</name>
    <address>Binary Avenue 1234 FL</address>
    <email>john@domain.com</email>
    <gender>
    <type>Male</type>
    </gender>
    </user>
    <user>
    <name>Janet Smith</name>
    <address>Crazy Bits Road 4568 CA</address>
    <email>janet@janet-domain.com</email>
    <gender>
    <type>Female</type>
    </gender>
    </user>
    </users>
    XML;

    As you can see, I created a new string of XML data, so you can have an accurate idea of how to access the child nodes of all the <gender> nodes. Now, take a look at the following script, which uses the “children()” method for performing this task:

    // example finding child nodes of <gender> nodes with the
    children() method
    require_once 'xml_string.php';
    if(!$xml=simplexml_load_string($xmlstr)){
        trigger_error('Error reading XML string',E_USER_ERROR);
    }
    foreach($xml->children() as $children){
        echo 'Name node found with the following value: '.$children-
    >name.'<br />';
        foreach($children->children() as $newchildren){
            if($newchildren->type!=''){
                echo 'Gender node has the following child node:
    '.$newchildren->type.'<br />';
            }
        }
    }

    On this occasion, the above script utilizes the “children()” method inside two “foreach” loops, in order to find all the child nodes that belong to the corresponding <gender> elements, which outputs the following result:

    Name node found with the following value: John Doe
    Gender node has the following child node: Male
    Name node found with the following value: Janet Smith
    Gender node has the following child node: Female

    Well, if the previous example is a little bit harder to understand, check out this one, which uses the following XML string and certainly is much simpler to read and code:

    $xmlstr=<<<XML
    <?xml version="1.0" encoding="iso-8859-1"?>
    <users>
    <user>
    <name>John Doe</name>
    <address>Binary Avenue 1234 FL</address>
    <email>john@john-domain.com</email>
    <gender type="male">1</gender>
    <gender type="female">2</gender>
    </user>
    <user>
    <name>Janet Smith</name>
    <address>Crazy Bits Road 4568 CA</address>
    <email>janet@janet-domain.com</email>
    <gender type="male">1</gender>
    <gender type="female">2</gender>
    </user>
    <user>
    <name>James Smith</name>
    <address>Socket Boulevard 7894 OH</address>
    <email>james@james-domain.com</email>
    <gender type="male">1</gender>
    <gender type="female">2</gender>
    </user>
    <user>
    <name>Silvia Wilson</name>
    <address>Protocol Avenue 5652 NY</address>
    <email>silvia@silvia-domain.com</email>
    <gender type="male">1</gender>
    <gender type="female">2</gender>
    </user>
    <user>
    <name>Alejandro Gervasio</name>
    <address>Boulevard of Objects 10101 AR</address>
    <email>alejandro@alejandro-domain.com</email>
    <gender type="male">1</gender>
    <gender type="female">2</gender>
    </user>
    </users>
    XML;

    require_once 'xml_string.php';
    if(!$xml=simplexml_load_string($xmlstr)){
        trigger_error('Error reading XML string',E_USER_ERROR);
    }
    foreach($xml->children() as $children){
        echo 'Name node with the following value '.$children->name.'<br />';
    }

    // displays the following output

    Name node with the following value John Doe
    Name node with the following value Janet Smith
    Name node with the following value James Smith
    Name node with the following value Silvia Wilson
    Name node with the following value Alejandro Gervasio

    Actually, the example shown above is rather trivial, but I just want you to grasp correctly the logic behind the “children()” method. Did you get it? I hope so.

    Finally, the two methods that I’d like to show you are called “attributes()” and “simple_import_dom()” respectively. Obviously, the first one is focused on retrieving all the attributes that correspond to a specific XML node, while the second one is useful for importing a new DOM document as XML data.

    With reference to the “attributes()” method, here is an example that teaches you how it can be implemented:

    $xmlstr=<<<XML
    <?xml version="1.0" encoding="iso-8859-1"?>
    <users>
    <user name="John Doe" address="Binary Avenue 1234 FL" email="john@john-domain.com">User1</user>
    <user name="Janet Smith" address="Crazy Bits Road 4568 CA" email="janet@janet-domain.com">User2</user>
    </users>
    XML;

    // example using the 'attributes()' method
    require_once 'xml_string.php';
    if(!$xml=simplexml_load_string($xmlstr)){
        trigger_error('Error reading XML string',E_USER_ERROR);
    }
    foreach($xml->user[0]->attributes() as $attr=>$value){
        echo 'Attribute '.$attr. ' found with the following value: '.$value.'<br />';
    }

    // displays the following output

    Attribute name found with the following value: John Doe
    Attribute address found with the following value: Binary Avenue
    1234 FL
    Attribute email found with the following value: john@john-
    domain.com

    As you can see, the “attributes()” method allows you to obtain all the attributes of a particular element within a XML string, which are returned as an associative array. In this case, I used basic XML data, so that you can easily understand how this method works.

    After demonstrating how the “attributes()” method does its thing, take a little break and examine the code snippet below, which shows how to implement the “simplexml_import_dom()” method:

    // example using the 'import_dom()' method
    $dom=new domDocument;
    if(!$dom->loadXML('<users><user><name>John
    Doe</name><address>Binary Avenue 1234
    FL</address><email>ohn@john-domain.com</email></user></users>')){
        trigger_error('Error loading XML string',E_USER_ERROR);
    }
    $xml=simplexml_import_dom($dom);
    echo 'Name of first user: '.$xml->user[0]->name;

    // displays the following output

    Name of first user: John Doe

    I purposely kept the above example rather simple, since the XML DOM is a huge topic, and certainly is out of the scope of this series. In short, the “simplexml_import_dom()” method can be used as an alternative way to load XML data strings onto an object. It lets you obtain results similar to using both the “simplexml_load_file()” and “simplexml_load_string()” methods. However, if you want to take the shortest path to parsing XML data, I suggest you to use these methods instead.

    Wrapping up

    Finally, we’re done. Over the course of this series, I introduced some of the most important functions that are included within the “simpleXML” PHP 5 extension. As you saw, this library eventually might fit the requirements of many applications that don’t demand complex parsing of XML data. If your next PHP-driven project falls under this category, go ahead and use it with no restrictions. See you in the next PHP tutorial!



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





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