HomePHP Page 4 - Searching and Replacing Nodes with SimpleXML in PHP 5
Replacing nodes within a XML string: using the “asXML()” method - PHP
Want to learn how to get the most out of the “simpleXML” extension that comes bundled with PHP 5? Welcome to the last part of the series “Working with simpleXML in PHP 5.” In three tutorials, this series covers topics ranging from the basics of parsing XML files with this library, to performing advanced tasks, such as searching, extracting and replacing nodes, and interoperating with the XML DOM.
Fortunately, the “simpleXML” extension isn’t limited to finding specific nodes within a given XML string or file. You can replace particular XML elements by using the cool “asXML()” method with ease. But first of all, let me show you how this method can be utilized for replacing nodes on the fly.
Using the same XML string that you saw in the previous sections, here is how this method is used for substituting a particular element:
// setting new values for specific nodes with the asXML() method require_once 'xml_string.php'; if(!$xml=simplexml_load_string($xmlstr)){ trigger_error('Error reading XML string',E_USER_ERROR); } $xml->user[0]->name='Jack Norton'; echo $xml->asXML();
If you examine the above script, you’ll possibly find it quite interesting. Please notice how the first user’s name is replaced with a different one by using the “asXML()” method. In this case, the logic of the script is very simple: first, the XML string is loaded onto an object, then the node being replaced is located by using the corresponding array syntax, and finally the “asXML()” method is invoked.
In fact, this method returns a new XML string, where the value of the selected node has been replaced with the new one, as shown below:
Jack Norton Binary Avenue 1234 FL John@domain.com 1 2 Janet Smith Crazy Bits Road 4568 CA Janet@janet-domain.com 1 2 James Smith Socket Boulevard 7894 OH James@james-domain.com 1 2 Silvia Wilson Protocol Avenue 5652 NY Silvia@silvia-domain.com 1 2 Alejandro Gervasio Boulevard of Objects 10101 AR Alejandro@alejandro-domain.com 1 2
As you’ll certainly agree, the behavior of this method is very convenient, since it only generates a new XML string on the fly, and leaves the original XML data untouched. Based on this example, try replacing other nodes and watch the different results that you’ll get in each case.
All right, now you know how to search and replace the nodes of a XML string, which is good and simple. So, what’s next? In the next section, I’ll be showing you how to use some additional methods of the “simpleXML” extension, in order to locate child nodes, access attributes and work with the XML DOM.