For more then one search this function will be helpfull:
<?php
class xpathExtension{
public static function getNodes($domDoc, $xpathString) {
$xp = new DOMXPath($domDoc);
$xp->registerNamespace('x', 'http://www.w3.org/1999/xhtml');
$xp->registerNamespace('xhtml', 'http://www.w3.org/1999/xhtml');
$xp->registerNamespace('i18n', 'http://apache.org/cocoon/i18n/2.1');
$ret = array();
$nodes = $xp->query($xpathString);
foreach ($nodes as $node) {
array_push($ret, $node);
}
return $ret;
}
}
$domDoc = new DOMDocument();
$domDoc->load("xmlFile.xml");
$xpathString = "//html/body/*[@class='text']";
$domNodeList = xpathExtension::getNodes($domDoc, $xpathString);
foreach($domNodeList as $domNode){
echo $domNode->nodeName;
}
?>
Thanks to:
https://svn.liip.ch/repos/public/okapi/core/trunk/inc/api/helpers/
xpath.php
The DOMXPath class
Introduction
Supports XPath 1.0
Class synopsis
Properties
- document
-
Prop description
Table of Contents
- DOMXPath::__construct — Creates a new DOMXPath object
- DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible.
- DOMXPath::query — Evaluates the given XPath expression
- DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
DOMXPath
ahsdg at NOSPAM dot pochta dot ru
22-Mar-2009 11:39
22-Mar-2009 11:39
Mark Omohundro, ajamyajax dot com
14-Dec-2008 05:15
14-Dec-2008 05:15
<?php
// to retrieve selected html data, try these DomXPath examples:
$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");
// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");
// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");
if (!is_null($elements)) {
foreach ($elements as $element) {
echo "<br/>[". $element->nodeName. "]";
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
?>
