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
$user = <<<XML
<user>
<username>Geeks123 </username>
<name>GeeksforGeeks</name>
<phone>+91-XXXXXXXXXX</phone>
<detail font-color= "blue" font-size= "24px" >
Noide India
</detail>
</user>
XML;
$xml = simplexml_load_string( $user );
echo "Base tag name: " . $xml ->getName() . "<br>" ;
foreach ( $xml ->children() as $child ) {
echo "child node: " . $child ->getName()
. " = " . $child . "</br>" ;
}
?>
|
Output:
Example 2:
php
<?php
$user = <<<XML
<user>
<username>Geeks123</username>
<name>GeeksforGeeks</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;
$xml = simplexml_load_string( $user );
getname_rec( $xml , 0);
function getname_rec( $xml , $depth ) {
print_space( $depth );
echo "tag name: " . $xml ->getName() . "<br>" ;
foreach ( $xml ->children() as $child ) {
if ( $child -> count () > 0) {
getname_rec( $child , $depth +1);
}
else {
print_space( $depth );
echo " child node: " . $child ->getName()
. " = " . $child . "</br>" ;
}
}
}
function print_space( $i ) {
for ( $x = 0; $x < $i *3; $x ++) {
echo " " ;
}
}
?>
|
Output:
Reference:https://www.php.net/manual/en/simplexmlelement.getname.php
Last Updated :
02 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...