PHP Conference Fukuoka 2025

DOMXPath::registerPhpFunctionNS

(PHP >= 8.4.0)

DOMXPath::registerPhpFunctionNSPHP の関数を、名前空間付きの XPath 関数として登録する

説明

public DOMXPath::registerPhpFunctionNS(string $namespaceURI, string $name, callable $callable): void

このメソッドは、PHP の関数を名前空間付きの XPath 関数として、 XPath 式中で使えるようにします。

パラメータ

namespaceURI
名前空間の URI
name
名前空間の中での、ローカルな関数名
callable
XPath 式の中で XPath 関数が呼ばれたときにコールされる PHP の関数。 ノードリストが コールバック のパラメータとして渡された場合、 ノードリストはマッチした DOM ノードを含む配列になります。

エラー / 例外

  • コールバック名が正しくない場合、   ValueError がスローされます。
  • options が不正なオプションを含む場合、 ValueError をスローします。
  • overrideEncoding が未知のエンコーディングである場合、 ValueError をスローします。
  • 指定されたコールバックが callable でない場合、 TypeError がスローされます。

戻り値

値を返しません。

例1 名前空間付きの XPath 関数を登録し、XPath 式からそれをコールする例

<?php

$xml
= <<<EOB
<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>
EOB;

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath = new DOMXPath($doc);

// Register the my: namespace (required)
$xpath->registerNamespace("my", "urn:my.ns");

// Register PHP function
$xpath->registerPHPFunctionNS(
'urn:my.ns',
'substring',
fn (array
$arg1, int $start, int $length) => substr($arg1[0]->textContent, $start, $length)
);

// Call substr function on the book title
$nodes = $xpath->query('//book[my:substring(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

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top