Extracting Information Using XPath
PYou want to make sophisticated queries of your XML data without parsing the document node by node.
Solution: Use XPath
XPath is available in SimpleXML
<?php
$s=simple_load_file('address-book.xml');
$emails=$s->xpath('/address-book/person/email');
foreach($emails as $email){
//do something with $email
}
?>
And in DOM
<?php
$dom=new DOMDocument;
$dom->load('address-book.xml');
$xpath=new DOMXPath($dom);
$email=$xpath->query('/address-book/person/email');
foreach($emails as $email){
//do something with $email
}
?>
As your XML files become increasingly complex and your parsing desires grow, using XPath is easier than filtering the data inside a foreach.
PHP has an XPath class that takes a DOM object as its constructor. You can then search the object and receive DOM nodes in reply. SimpleXML also supports XPath, and it's easier to use because it's integrated into the SimpleXML object. DOM supports XPath queries, but you do not perform the query directly on the DOM object itself.
In contrast to DOM, all SimpleXML objects have an integrated xpath() method. Calling this method queries the current object using XPath and returns a SimpleXML object containing the matching nodes, so you don't need to instantiate another object to use XPath. The method's one argument is your XPath query.
SimpleXML handles the more complicated example too. Since xpath() returns SimpleXML objects, you can query them directly.
Solution: Use XPath
XPath is available in SimpleXML
<?php
$s=simple_load_file('address-book.xml');
$emails=$s->xpath('/address-book/person/email');
foreach($emails as $email){
//do something with $email
}
?>
And in DOM
<?php
$dom=new DOMDocument;
$dom->load('address-book.xml');
$xpath=new DOMXPath($dom);
$email=$xpath->query('/address-book/person/email');
foreach($emails as $email){
//do something with $email
}
?>
As your XML files become increasingly complex and your parsing desires grow, using XPath is easier than filtering the data inside a foreach.
PHP has an XPath class that takes a DOM object as its constructor. You can then search the object and receive DOM nodes in reply. SimpleXML also supports XPath, and it's easier to use because it's integrated into the SimpleXML object. DOM supports XPath queries, but you do not perform the query directly on the DOM object itself.
In contrast to DOM, all SimpleXML objects have an integrated xpath() method. Calling this method queries the current object using XPath and returns a SimpleXML object containing the matching nodes, so you don't need to instantiate another object to use XPath. The method's one argument is your XPath query.
SimpleXML handles the more complicated example too. Since xpath() returns SimpleXML objects, you can query them directly.
Comments
Post a Comment