Searching and Replacing Nodes with SimpleXML in PHP 5 - Finding nodes inside a XML string: using the “Xpath()” method (
Page 3 of 5 )
With regard to the localization of specific nodes within an XML string, the “simpleXML” extension comes with the handy “Xpath()” method, which allows you to locate particular nodes and iterate over them by utilizing a “foreach” loop. The following example demonstrates how to achieve this, so take a look at its source code:
// search <name> nodes
require_once 'xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
trigger_error('Error reading XML string',E_USER_ERROR);
}
foreach($xml->xpath('//name') as $names){
echo 'Name node found with a value of '.$names.'<br />';
}
The script listed above uses the “Xpath()” method to find all the <name> nodes contained within the previous sample XML string. Notice the remarkable flexibility provided by this method, when searching nodes that match a given name. Simple and powerful, right?
And, of course, here is the corresponding output of the prior code snippet:
Name node found with a value of John Doe
Name node found with a value of Janet Smith
Name node found with a value of James Smith
Name node found with a value of Silvia Wilson
Name node found with a value of Alejandro Gervasio
In case the above example isn’t clear enough to you, here's an additional one, which searches for and displays all the <email> nodes included within the respective sample XML data string:
// search <email> nodes
require_once 'xml_string.php';
if(!$xml=simplexml_load_string($xmlstr)){
trigger_error('Error reading XML string',E_USER_ERROR);
}
foreach($xml->xpath('//email') as $email){
echo 'Email node found with a value of '.$email.'<br />';
}
As you may have guessed, all the <email> nodes are properly located and displayed as follows:
Email node found with a value of john@john-domain.com
Email node found with a value of janet@janet-domain.com
Email node found with a value of james@james-domain.com
Email node found with a value of silvia@silvia-domain.com
Email node found with a value of alejandro@alejandro-domain.com
At this stage, hopefully you have learned how to search specific nodes within a given XML string by using the handy “Xpath()” method. Now, it’s time to see how these nodes can be replaced appropriately. Therefore, go ahead and read the next section.