The DOMElement::getElementsByTagNameNS() function is an inbuilt function in PHP which is used to get all the descendant elements with a given localName and namespaceURI.
Syntax:
DOMNodeList DOMElement::getElementsByTagNameNS( string $namespaceURI, string $localName )
Parameters: This function accept two parameters as mentioned above and described below:
- $namespaceURI: It specifies the namespace URI.
- $localName: It specifies the local name.
Return Value: This function returns a DOMNodeList value containing all matched elements in the order in which they are encountered in a preorder traversal of this element tree.
Below given programs illustrate the DOMElement::getElementsByTagNameNS() function in PHP:
Program 1:
<?php // Create a new DOMDocument $dom = new DOMDocument();
// Load the XML $dom ->loadXML("<?xml version=\"1.0\"?>
<root> <div xmlns:x=\"my_namespace\">
<x:h1 x:style=\"color:red;\">
Hello, this is my red heading.
</x:h1>
<x:h1 x:style=\"color:green;\">
Hello, this is my green heading.
</x:h1>
<x:h1 x:style=\"color:blue;\">
Hello, this is my blue heading.
</x:h1>
</div>
<div xmlns:y=\"another_namespace\">
<y:h1 y:style=\"color:red;\">
Hello, this is my new red heading.
</y:h1>
<y:h1 y:style=\"color:green;\">
Hello, this is my new green heading.
</y:h1>
<y:h1 y:style=\"color:blue;\">
Hello, this is my new blue heading.
</y:h1>
</div>
</root>"); // Get the elements with h1 tag from // specific namespace $nodeList = $dom ->getElementsByTagNameNS(
'my_namespace' , 'h1' );
foreach ( $nodeList as $node ) {
echo $node ->getAttribute( 'x:style' ) . '<br>' ;
} ?> |
Output:
color:red;
color:green;
color:blue;
Program 2:
<?php // Create a new DOMDocument $dom = new DOMDocument();
// Load the XML $dom ->loadXML("<?xml version=\"1.0\"?>
<root> <div xmlns:x=\"my_namespace\">
<x:p>HELLO.</x:p>
<x:p>NEW.</x:p>
<x:p>WORLD.</x:p>
</div>
<div xmlns:y=\"g4g_namespace\">
<y:p>GEEKS</y:p>
<y:p>FOR</y:p>
<y:p>GEEKS</y:p>
</div>
</root>"); // Get the elements $nodeList = $dom ->getElementsByTagNameNS(
'g4g_namespace' , 'p' );
foreach ( $nodeList as $node ) {
echo $node ->textContent . '<br>' ;
} ?> |
Output:
GEEKS
FOR
GEEKS
Reference: https://www.php.net/manual/en/domelement.getelementsbytagnamens.php