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:
php
Output:
php
Output:
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.
<?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>';
}
?>
color:red;Program 2:
color:green;
color:blue;
<?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>';
}
?>
GEEKSReference: https://www.php.net/manual/en/domelement.getelementsbytagnamens.php
FOR
GEEKS