php-doc-en/reference/dom/functions/dom-domxpath-query.xml

121 lines
3.1 KiB
XML
Raw Normal View History

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.7 $ -->
<refentry id="function.dom-domxpath-query">
<refnamediv>
<refname>DOMXPath->query</refname>
<refpurpose>
Evaluates the given XPath expression
</refpurpose>
</refnamediv>
<refsect1>
&reftitle.description;
<classsynopsis>
<ooclass><classname>DOMXPath</classname></ooclass>
<methodsynopsis>
<type>DOMNodeList</type>
<methodname>query</methodname>
<methodparam><type>string</type><parameter>expression</parameter></methodparam>
<methodparam choice="opt"><type>DOMNode</type><parameter>contextnode</parameter></methodparam>
</methodsynopsis>
</classsynopsis>
<para>
Returns a <classname>DOMNodeList</classname> containing all nodes matching
the given XPath <parameter>expression</parameter>. Any expression which do
not return nodes will return an empty <classname>DOMNodeList</classname>.
</para>
<para>
<example>
<title>Getting all the english books</title>
<programlisting role="php">
<![CDATA[
<?php
$doc = new DOMDocument;
// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;
$doc->Load('book.xml');
$xpath = new DOMXPath($doc);
// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';
$entries = $xpath->query($query);
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck
]]>
</screen>
</example>
</para>
<para>
The optional <parameter>contextnode</parameter> can be specified for doing
relative XPath queries. By default, the queries are relative to the root
element. Knowing that, we can rewrite our previous example as follow:
</para>
<para>
<example>
<title>Using the context node</title>
<programlisting role="php">
<![CDATA[
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->Load('book.xml');
$xpath = new DOMXPath($doc);
$tbody = $doc->getElementsByTagName('tbody')->item(0);
// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';
$entries = $xpath->query($query, $tbody);
foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>
]]>
</programlisting>
</example>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->