PHP | SimpleXMLElement::getName() Function

Pre-requisite: Read XML basics
The SimpleXMLElement::getName() function is an inbuilt function in PHP which returns the name of the xml element.
Syntax:Â
Â
string SimpleXMLElement::getName( void )
Parameter: This function does not accept any parameter.
Return Value: It returns a string which represents the name of XML element of a SimpleXMLElement object.
Note: This function is available on PHP 5.1.3 and newer version.
Below programs illustrate the SimpleXMLElement::getName() function in PHP:
Example 1:Â
Â
php
<?phpÂ
// Loading XML document to $user$user = <<<XML<user>    <username>Geeks123 </username>    <name>zambiatek</name>    <phone>+91-XXXXXXXXXX</phone>    <detail font-color="blue" font-size="24px">        Noide India    </detail></user>XML;Â
// Loading string as simple xml object$xml = simplexml_load_string($user);Â
// Display the name of elementecho "Base tag name: " . $xml->getName() . "<br>";Â
foreach($xml->children() as $child) {Â Â Â Â echo "child node: " . $child->getName() Â Â Â Â Â Â Â Â . " = " . $child . "</br>";}Â
?> |
Output:Â
Â
Example 2:Â
Â
php
<?phpÂ
// Loading XML document to $user$user = <<<XML<user>    <username>Geeks123</username>    <name>zambiatek</name>    <phone>+91-XXXXXXXXXX</phone>    <detail font-color="blue" font-size="24px">        Computer science portal    </detail>    <address>        <city>Noida</city>        <country>India</country>    </address></user>XML;Â
// Loading string as simple xml object$xml = simplexml_load_string($user);Â
// Recursive function calledgetname_rec($xml, 0);  // The getname_rec() function definition function getname_rec($xml, $depth) {         print_space($depth);         echo "tag name: " . $xml->getName() . "<br>";         foreach($xml->children() as $child) {        if($child->count() > 0) {                         // If there exists any child of current node            getname_rec($child, $depth+1);        }        else {                          // If there is no child of the current node            print_space($depth);            echo " child node: " . $child->getName()                    . " = " . $child . "</br>";        }    }}Â
// Function to print 3X$i number of spacesfunction print_space($i) {Â Â Â Â for($x = 0; $x < $i*3; $x++) {Â Â Â Â Â Â Â Â echo "Â ";Â Â Â Â }}Â
?> |
Output:Â
Â
Reference:https://www.php.net/manual/en/simplexmlelement.getname.php
Â




