Movatterモバイル変換


[0]ホーム

URL:


    DOMXPath::__construct »
    « DOMText::splitText

    The DOMXPath class

    (PHP 5, PHP 7, PHP 8)

    Introduction

    Allows to use XPath 1.0 queries on HTML or XML documents.

    Class synopsis

    classDOMXPath {
    /* Properties */
    publicreadonlyDOMDocument$document;
    /* Methods */
    public__construct(DOMDocument$document,bool$registerNodeNS =true)
    publicevaluate(string$expression,?DOMNode$contextNode =null,bool$registerNodeNS =true):mixed
    publicquery(string$expression,?DOMNode$contextNode =null,bool$registerNodeNS =true):mixed
    publicstaticquote(string$str):string
    publicregisterNamespace(string$prefix,string$namespace):bool
    publicregisterPhpFunctionNS(string$namespaceURI,string$name,callable$callable):void
    }

    Properties

    document
    The document that is linked to this object.
    registerNodeNamespaces
    When set totrue, namespaces in the node are registered.

    Changelog

    VersionDescription
    8.4.0 It is no longer possible to clone aDOMXPath object. Doing so will result in an exception being thrown. Prior to PHP 8.4.0 this resulted in an unusable object.
    8.0.0 TheregisterNodeNamespaces property has been added.

    Table of Contents

    Found A Problem?

    Learn How To Improve This PageSubmit a Pull RequestReport a Bug
    add a note

    User Contributed Notes5 notes

    Mark Omohundro, ajamyajax dot com
    16 years ago
    <?php// to retrieve selected html data, try these DomXPath examples:$file=$DOCUMENT_ROOT."test.html";$doc= newDOMDocument();$doc->loadHTMLFile($file);$xpath= newDOMXpath($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 ($elementsas$element) {    echo"<br/>[".$element->nodeName."]";$nodes=$element->childNodes;    foreach ($nodesas$node) {      echo$node->nodeValue."\n";    }  }}?>
    TechNyquist
    5 years ago
    When working with XML (as a strict format) might be very important to give a namespace to XPath object in order to make it work properly.I was experiencing "query" always returning empty node lists, it could not find anything. Only a broad "//*" was able to show off only the root element.Then found out that registering the namespace reported in the "xmlns" attribute of the root element in the XPath object, and writing the namespace near the elements name, made it work properly.So for an XML like this (from a sitemap):<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">    <url>        <loc>http://example.com/index.php</loc>        <lastmod>2005-01-01</lastmod>        <changefreq>monthly</changefreq>        <priority>0.5</priority>    </url></urlset>I needed the following XPath configuration:<?php    $doc= newDOMDocument;$doc->load("sitemap.xml");$xpath= newDOMXPath($doc);$xpath->registerNamespace('ns','http://www.sitemaps.org/schemas/sitemap/0.9');$nodes=$xpath->query('//ns:urlset/ns:url');?>Then again, that "xmlns" could be provided dynamically from the root element attribute of course.
    peter at softcoded dot com
    8 years ago
    You may not always know at runtime whether your file hasa namespace or not. This can make it difficult to createXPath queries. Use the seriously underdocumented"namespaceURI" property of the documentElement of aDOMDocument to determine if there is a namespace.Use code such as the following:$doc = new DOMDocument();$doc->load($file);$xpath = new DOMXPath($doc);$ns = $doc->documentElement->namespaceURI;if($ns) {  $xpath->registerNamespace("ns", $ns);  $nodes = $xpath->query("//ns:em[@class='glossterm']");} else {  $nodes = $xpath->query("//em[@class='glossterm']");}//look at nodes here
    peter at softcoded dot com
    8 years ago
    Using XPath expressions can save a lot of programmingand allow you to home in on only the nodes you want.Suppose you want to delete all empty <p> tags.If you create a query using the following XPath expression,you can find <p> tags that do not have any text(other than spaces), any attributes,any children or comments:$expression = "//p[not(@*)     and not(*)    and not(./comment())   and normalize-space(text())='']";   This expression will only find para tags that look like:<p>[any number of spaces]</p><p></p>Imagine the code you would have to add if you usedDOMDocument::getElementsByTagName("p") instead.
    archimedix32783262 at mailinator dot com
    11 years ago
    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.
    add a note
    To Top
    and to navigate •Enter to select •Esc to close •/ to open
    PressEnter without selection to search using Google

    [8]ページ先頭

    ©2009-2025 Movatter.jp