文字

The DOMXPath class

(PHP 5, PHP 7)

简介

Supports XPath 1.0

类摘要

DOMXPath {
public DOMDocument $document ;
public __construct ( DOMDocument $doc )
public mixed evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public DOMNodeList query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = true ]] )
public bool registerNamespace ( string $prefix , string $namespaceURI )
public void registerPhpFunctions ([ mixed $restrict ] )
}

属性

document

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

用户评论:

[#1] archimedix32783262 at mailinator dot com [2014-09-03 12:03:48]

Note that evaluate() will use the same encoding as the XML document.

So if you have a UTF-16 XML, you will have to query using UTF-16 strings.

You can use iconv() to convert from your code's encoding to the target encoding for better legibility.

[#2] dhz [2011-01-05 10:47:20]

I just spent far too much time chasing this one....

When running an xpath query on a table be careful about table internal nodes (ie: <tr></tr>, and <td></td>).  If the master <table> tag is missing, then query() (and likely evaluate() also) will return unexpected results.

I had a DOMNode with a structure like this:

<td>
    <table></table>
    <table>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</td>

Upon which I was trying to do a relative query (ie: <?php $xpath_obj->query('my/x/path', $relative_node); ?>).

But because of the lone outer <td></td> tags, the inner tags were being invalidated, while the nodes were still recognized.  Meaning that the following query would work:

<?php $xpath_obj->query('*[2]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";
    }
  }
}
?>

上一篇: 下一篇: