PHP | DOMXPath registerPhpFunctions() Function
Last Updated :
13 Mar, 2020
The DOMXPath::registerPhpFunctions() function is an inbuilt function in PHP which is used to enable the ability to use PHP functions within XPath expressions.
Syntax:
void DOMXPath::registerPhpFunctions( mixed $restrict )
Parameters: This function accepts an optional single parameter $restrict which holds the function to restrict.
Return Value: This function does not return any value.
Below given programs illustrate the DOMXPath::registerPhpFunctions() function in PHP:
Program 1:
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "UTF-8" ?>
<books>
<book>
<title>FOO BAR</title>
<author>Mr. A</author>
<author>Mr. B</author>
</book>
<book>
<title>FOO BAZ</title>
<author>Mr. C</author>
</book>
</books>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$xpath ->registerNamespace( "php" ,
$xpath ->registerPHPFunctions();
$query = '//book[php:functionString('
. '"substr", title, 0, 3) = "FOO"]' ;
$entries = $xpath ->evaluate( $query );
echo "Found $entries->length books"
. " starting with 'FOO':\n" ;
foreach ( $entries as $node ) {
$title = $node ->getElementsByTagName(
"title" )->item(0)->nodeValue;
echo "<br>$title" ;
}
?>
|
Output:
Found 2 books starting with 'FOO':
FOO BAR
FOO BAZ
Program 2:
<?php
$document = new DOMDocument();
$xml = <<<XML
<?xml version= "1.0" encoding= "UTF-8" ?>
<books>
<book>
<title>FOO BAR</title>
<author>Mr. A</author>
<author>Mr. B</author>
</book>
<book>
<title>FOO BAZ</title>
<author>Mr. C</author>
</book>
</books>
XML;
$document ->loadXML( $xml );
$xpath = new DOMXPath( $document );
$xpath ->registerNamespace( "php" ,
$xpath ->registerPHPFunctions();
$query = '//book[php:function('
. '"has_multiple", author)]' ;
$entries = $xpath ->evaluate( $query );
echo "Found $entries->length books "
. "with multiple authors:\n" ;
foreach ( $entries as $node ) {
$title = $node ->getElementsByTagName(
"title" )->item(0)->nodeValue;
echo "<br>$title" ;
}
function has_multiple( $nodes ) {
return count ( $nodes ) > 1;
}
?>
|
Output:
Found 1 books with multiple authors:
FOO BAR
Reference: https://www.php.net/manual/en/domxpath.registerphpfunctions.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...