(PHP >= 8.4.0)
DOMXPath::registerPhpFunctionNS — Enregistre une fonction PHP en tant que fonction XPath dans un espace de noms
$namespaceURI
, string $name
, callable $callable
): voidCette méthode permet d'utiliser une fonction PHP en tant que fonction XPath dans les expressions XPath.
namespaceURI
name
callable
options
contient une option invalide.
overrideEncoding
utilise un encodage inconnu.
Aucune valeur n'est retournée.
Exemple #1 Enregistre une fonction XPath dans un espace de noms et l'appelle depuis l'expression 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);
// Enregistre l'espace de noms my: (obligatoire)
$xpath->registerNamespace("my", "urn:my.ns");
// Enregistre les fonctions PHP
$xpath->registerPhpFunctionNS(
'urn:my.ns',
'substring',
fn (array $arg1, int $start, int $length) => substr($arg1[0]->textContent, $start, $length)
);
// Appel de la fonction substr sur le titre du livre
$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";
}
?>
Résultat de l'exemple ci-dessus est similaire à :
Found 2 books starting with 'PHP': PHP Basics by Jim Smith PHP Secrets by Jenny Smythe