16 May, 2010

Xpath in PHP

XPath allows you to retrieve any infromation from xml data. Working with xpath in php is quite simple in some sense
and quite complex in some sense. Some simple xpath queries are explained as a beginning for xpath using php.
Consider following XML file, saved as test.xml




Professinal PHP
Someone not me

One
Two


Beginning PHP
PHP with Ajax
PHP .NET



Now to load the xml file and perform XPath query


$doc = new DOMDocument();
//load the xml file
$doc->load("test.xml");

//create XPath
$newXpath = new DOMXPath($doc);
//get all the title tags from the loaded xml
$books = $newXpath->query("/books/book/title");
//show all the title values such as Professional PHP, Beginning PHP, PHP with Ajax and PHP .NET
foreach($books as $book) {
echo $book->nodeValue."
";
}

//now to get only the title that has certain attributes value such as isbn value in this case
//we do the following, following code shows title Beginning PHP
$onlyBook = $newXpath->query("/books/book[@isbn='1234']/title");

//to get title depending on some values, such as
//following code shows Professional PHP
$firstTitlte = $newXpath->query("/books/book/srcs[src='One' or src='Two']/../title");
?>

No comments: