Loading XML Strings with simpleXML in PHP 5

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.

Introduction

For those of you who didn’t read the first article, let me put you quickly in the right context. Over the course of the previous tutorial, I explained the basics of the excellent “simpleXML” library included with PHP 5, introducing the use of the “simplexml_load_file()” function. This can be remarkably useful if you need to add basic XML parsing capabilities to your PHP 5 applications, but don’t wish to develop a full-blown XML parser.

Based on the capacity provided by the “simplexml_load_file()” function, I went through the development of different practical examples, aimed at illustrating how a specific XML file can be basically parsed in different ways, including the loading of XML data onto objects, as well as the localization (and eventually the extraction) of particular nodes within a file. In addition, due to the ubiquitous nature of this extension, I showed how to build a basic XML parsing class, which worked as a simple wrapper for the “simplexml_load_file()” function, allowing the retrieval of different nodes contained within an XML file, and more.

Hopefully, all the examples shown in the previous article have provided you with the right pointers to start using the “simpleXML” library with only minor hassles, therefore in this second tutorial, I’ll continue exploring other helpful functions, focused primarily on loading XML data strings, as well as searching and accessing nodes.

Provided that all the topics that I mentioned before already caught your attention, let’s continue exploring the handy functions included within the “simpleXML” extension. Let’s get started!

{mospagebreak title=Parsing basic XML strings: using the “simplexml_load_string()” function}

In order to demonstrate how XML strings can be loaded onto regular objects for further processing, I’ll use the sample XML file that I built in the first article, as the foundation for creating a basic XML data string. As you’ll probably recall, this XML file looked like this:

<?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>
</user>
<user>
<name>Janet Smith</name>
<address>Crazy Bits Road 4568 CA</address>
<email>janet@janet-domain.com</email>
</user>
<user>
<name>James Smith</name>
<address>Socket Boulevard 7894 OH</address>
<email>james@james-domain.com</email>
</user>
<user>
<name>Silvia Wilson</name>
<address>Protocol Avenue 5652 NY</address>
<email>silvia@silvia-domain.com</email>
</user>
<user>
<name>Alejandro Gervasio</name>
<address>Boulevard of Objects 10101 AR</address>
<email>alejandro@alejandro-domain.com</email>
</user>
</users>

As you can see, the above XML file is pretty understandable, since it contains a few simple <user> nodes that also include some additional child nodes. Now, based on the structure of this file, I’m going to create a new file, which will contain the following XML 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@john-domain.com</email>
</user>
<user>
<name>Janet Smith</name>
<address>Crazy Bits Road 4568 CA</address>
<email>janet@janet-domain.com</email>
</user>
<user>
<name>James Smith</name>
<address>Socket Boulevard 7894 OH</address>
<email>james@james-domain.com</email>
</user>
<user>
<name>Silvia Wilson</name>
<address>Protocol Avenue 5652 NY</address>
<email>silvia@silvia-domain.com</email>
</user>
<user>
<name>Alejandro Gervasio</name>
<address>Boulevard of Objects 10101 AR</address>
<email>alejandro@alejandro-domain.com</email>
</user>
</users>
XML;

Well, creating a sample XML string wasn’t a big deal, right? Now that I have an XML data string to work with, I’ll use the “simplexml_load_string()” function that comes with the “simpleXML” library to load the corresponding XML data onto a regular object. Take a look at the following example:

// example using ‘simplexml_load_string()’ function
// include XML string
require_once ‘xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
    trigger_error(‘Error reading XML string’,E_USER_ERROR);
}
echo ‘Displaying contents of XML file…<br />';
foreach($xml as $user){
    echo ‘Name: ‘.$user->name.’ Address: ‘.$user->address.’
Email: ‘.$user->email.'<br />';
}

In this case, after including the pertinent PHP file that contains the previous XML string (called “xml_string.php”), the above script uses the “simplexml_load_string()” function, first for loading XML data onto the $xml object, and then for displaying the values of the corresponding child nodes.

As you can see, these child nodes are accessed as object properties, which makes it extremely easy to traverse a given XML string, something similar to the examples that you learned regarding the implementation of the “simplexml_load_file()” function.

As you may have guessed, the output of the previous example is as follows:

Displaying contents of XML file…
Name: John Doe Address: Binary Avenue 1234 FL Email:
john@domain.com
Name: Janet Smith Address: Crazy Bits Road 4568 CA Email:
janet@janet-domain.com
Name: James Smith Address: Socket Boulevard 7894 OH Email:
james@james-domain.com
Name: Silvia Wilson Address: Protocol Avenue 5652 NY Email:
silvia@silvia-domain.com
Name: Alejandro Gervasio Address: Boulevard of Objects 10101 AR
Email: alejandro@alejandro-domain.com

Don’t tell me that wasn’t pretty cool! The “simplexml_load_string()” function will allow you to load an XML string onto an object and traverse it by a regular “foreach” loop. Are you starting to see why this library is called “simpleXML”?

At this point, you saw how easy it is to load XML strings onto objects, so let’s move one and see how specific nodes can be accessed as regular object properties. That’s exactly the subject of the next section, therefore click on the link below to learn more about this.

{mospagebreak title=More examples with the “simplexml_load_string()” function: accessing parent and child nodes}

By using the XML string that I built in the previous section, it’s possible to set up an example that shows how to access particular nodes within the given string and how to display them accordingly. With regard to this, the following example illustrates the process for retrieving the values of all the <email> nodes contained in the pertinent XML string:

// displays contents of <email> nodes
require_once ‘xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
    trigger_error(‘Error reading XML string’,E_USER_ERROR);
}
echo ‘Displaying email addresses of XML string…<br />';
foreach($xml as $user){
    echo ‘Values of email nodes: ‘.$user->email.'<br />';
}

As shown above, displaying the values of all the <email> nodes is actually a breeze. After loading the XML string onto an object, the corresponding nodes are accessed as object properties, which results in the following output:

Displaying email addresses of XML string…
Values of email nodes: john@domain.com
Values of email nodes: janet@janet-domain.com
Values of email nodes: james@james-domain.com
Values of email nodes: silvia@silvia-domain.com
Values of email nodes: alejandro@alejandro-domain.com

All right, since the prior example speaks for itself, take a look at the next one, which shows how to locate a specific node within the XML string and displays the corresponding data using the typical array notation:

// locates a specific node and displays email of a given user
require_once ‘xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
    trigger_error(‘Error reading XML string’,E_USER_ERROR);
}
// displays email of an user
echo ‘Displaying email of user ‘.$xml->user[2]->name.'<br />';
echo $xml->user[2]->email;

As you’ll recall, when I explained how the “simplexml_load_file()” function worked, XML nodes can be easily accessed via a regular array syntax, as demonstrated by the example listed above. In this particular case, I opted to display data about the third <user> node:

Displaying email of user James Smith
james@james-domain.com

Finally, let me show you one slightly more complex example that also uses the “simplexml_load_string()” function. For instance, suppose that you have the following XML 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@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;

Essentially, what I did here was add an extra <gender> node to the previous XML string, which has a “type” attribute. Now, to my own pleasure and of course yours, the “simpleXML” extension provides you with the ability to access node attributes as associative arrays. Want to see how this is done? The following example clearly shows how this process is performed:

// example accessing attributes as array elements
require_once ‘xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
    trigger_error(‘Error reading XML string’,E_USER_ERROR);
}
echo ‘Displaying gender attribute of second user…<br />';
foreach($xml->user[0]->gender as $gender){
    echo ‘Gender: ‘.$gender['type'].'<br />';
}

As you can see, the above script first loads the corresponding XML string onto the $xml object, then reaches the second user, and finally displays the values of the <type> attributes associated with the respective <gender> nodes. Attributes are accessed via an associative array notation, as listed below:

echo ‘Gender: ‘.$gender['type'].'<br />';

Lastly, the above expression displays the following information:

Displaying gender attribute of second user…
Gender: male
Gender: female


Definitely, accessing nodes and attributes is a no-brainer process if you use the “simpleXML” extension, which has been hopefully demonstrated by the hands-on examples you learned before. Since all the code samples I wrote have followed a procedural approach, in the last section of this article I’ll build up a simple XML parsing class that utilizes the “simplexml_load_string()” function for parsing XML strings.

To find out how this will be achieved, go ahead and read the next section.

{mospagebreak title=Parsing XML strings by an object-oriented approach: building a PHP 5 XML parsing class}

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!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort