Using XPath with DOM in a basic example : xpath « XML « PHP






Using XPath with DOM in a basic example

 
<?
$dom = new DOMDocument;
$dom->load('address-book.xml');
$xpath = new DOMXPath($dom);
$emails = $xpath->query('/address-book/person/email');

foreach ($emails as $e) {
    $email = $e->firstChild->nodeValue;
    // do something with $email
}
?>
//
<?xml version="1.0"?>
<address-book>
    <person id="1">
        <firstname>D</firstname>
        <lastname>S</lastname>
        <city>New York</city>
        <state>NY</state>
        <email>s@php.net</email>
    </person>

    <person id="2">
        <firstname>A</firstname>
        <lastname>T</lastname>
        <city>San Francisco</city>
        <state>CA</state>
        <email>a@php.net</email>
    </person>
</address-book>
  
  








Related examples in the same category

1.Combine it with an XPath search
2.xpath.php
3.Using XPath and DOM
4.Using XPath and SimpleXML in a basic example
5.Using XPath with SimpleXML in a more complicated example
6.XPath DOM Query
7.XPath can be used to filter your results according to any values
8.Searching and Filtering with XPath