When using DOMXPath and having a default namespace. Consider using an intermediate function to add the default namespace to all queries:
<?php
// The default namespace: x:xmlns="http://..."
$path="/Book/Title";
$path=preg_replace("\/([a-zA-Z])","/x:$1",$path);
// Result: /x:Book/x:Title
?>
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::registerPhpFunctions — Register PHP functions as XPath functions
DOMXPath
david at lionhead dot nl
11-Aug-2009 03:33
11-Aug-2009 03:33
ahsdg at NOSPAM dot pochta dot ru
23-Mar-2009 12:39
23-Mar-2009 12:39
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
Mark Omohundro, ajamyajax dot com
14-Dec-2008 06:15
14-Dec-2008 06: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";
}
}
}
?>
