DOMXPath::registerNamespace
DOM 関数
DOMXPath
PHP Manual

# DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

### 説明

public void DOMXPath::registerPhpFunctions ([ mixed `$restrict` ] )

This method enables the ability to use PHP functions within XPath expressions.

### パラメータ

`restrict`

  Use this parameter to only allow certain functions to be called from XPath.

  This parameter can be either a string (a function name) or an array of function names.

### 返り値

値を返しません。

### 例

The following examples use book.xml which contains the following:

例1 book.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <books>
     <book>
      <title>PHP Basics</title>
      <author>Jim Smith</author>
      <author>Jane Smith</author>
     </book>
     <book>
      <title>PHP Secrets</title>
      <author>Jenny Smythe</author>
     </book>
     <book>
      <title>XML basics</title>
      <author>Joe Black</author>
     </book>
    </books>

例2 DOMXPath::registerPHPFunctions with php:functionString

`<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();
// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');
echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title by $author\n";
}
?>`

上の例の出力は、 たとえば以下のようになります。

    Found 2 books starting with 'PHP':
    PHP Basics by Jim Smith
    PHP Secrets by Jenny Smythe

例3 DOMXPath::registerPHPFunctions with php:function

`<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");
function has_multiple($nodes) {
// Return true if more than one author
return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');
echo "Books with multiple authors:\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}
?>`

上の例の出力は、 たとえば以下のようになります。

    Books with multiple authors:
    PHP Basics

### 参考

- DOMXPath::registerNamespace - DOMXPath オブジェクトの名前空間を登録する
- DOMXPath::query - 与えられた XPath 式を評価する
- DOMXPath::evaluate - 与えられた XPath 式を評価し、可能であれば結果を返す

DOMXPath::registerNamespace
DOM 関数
DOMXPath
PHP Manual