XPath examples
xpath-examples.php:
<?php
//load xml document
$dom = new DomDocument();
$dom->load("examples/books.xml");

//create DOMXPath object

function doQuery$title$query) {
    global 
$dom;
    
$xpath = new Domxpath($dom);
    
    
$result $xpath->query($query);
    print 
"-----------\n";
    print 
"<font color='blue'>$title</font>\n";
    print 
"$query\n";
    print 
"-----------\n";
    foreach(
$result as $node) {
        
        if(
$node instanceof DomNode) {
            print 
htmlentities($dom->saveXML($node)) . "\n";
        } else {
            
print_r$node) ."\n";
        }
        print 
"--\n";
    }
}

doQuery("XPath is like a file system","/books/book/title");
doQuery("// matches all nodes, which fullfill the following criteria","//title");
doQuery("The star * selects all nodes on that level","/books/book/*");
doQuery("Square brackets can further specifiy the nodes","/books/book[1]");
doQuery("The last book","/books/book[last()]");
doQuery("Attributes are prefixed by a @","/books/book/@isbn");
doQuery("Values of attributes can be used as selection criteria.","/books/book[@id = 2]");
doQuery("with count() the resulting nodes can be counted
 (does not work with query()) "
,"count(//books)");
doQuery("name() returns the node name","//*[name() = 'title']");
doQuery("Several paths can be combined with | separator.","//title | //year");
doQuery("The descendant axis contains the descendants of the context node","/books/descendant::*");
doQuery("The parent axis contains the parent of the context node","/books/book[position() = 1]/title/parent::*");
doQuery("The following-sibling axis contains all the following siblings of the context node.","/books/book[position() = 1]/title/following-sibling::*");
doQuery("contains() checks, if a node contains the needle",'//book[contains(dc:subject,"System")]');
doQuery("starts-with() checks, if a node starts with the needle",'//book[contains(dc:subject,"Operating")]');
 
XPath examples © copyright 2004  Bitflux GmbH