Function SimpleXMLElement::getName() - it is a built-in function in PHP that returns the xml element name.
Syntax:string SimpleXMLElement::getName (void)
Parameter:This function takes no parameters.
Return Value:Returns a string that represents the XML element name of the SimpleXMLElement .
Note.This function is available in PHP 5.1.3 and later.The following programs illustrate the SimpleXMLElement::getName() function in PHP:
Example 1:
// Load the XML document into $user
$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;
// Load the string as a simple xml object
$xml
= simplexml_load_string (
$user
);
// Show element name
echo
"Base tag name:"
.
$xml
-> getName().
"< br >"
;
foreach
(
$xml
-> children()
as
$child
) {
echo
"child node:"
.
$child
-> getName()
.
"="
.
$child
.
"< / br >"
;
}
?>
Output: Example 2:
// Loading XML document in $user
$user
= < < < XML
< user >
< username > Geeks123 < / username >
< name > GeeksforGeeks < / name >
< phone > + 91-XXXXXXXXXX < / phone >
< detail font-color =
"blue"
font-size =
"24px"
>
Computer science portal
< / detail >
< city > Noida < / city >
< country > India < / country >
< / address >
< / user >
XML;
// Load the string as a simple xml object
$xml
= simplexml_load_string (
$user
);
// Recursive function is called
getname_rec (
$xml
, 0);
// Definition of the getname_rec() function
function
getname_rec (
$xml
,
$depth
) {
print_space (
$depth
);
echo
" tag name: "
.
$xml
-> getName().
"< br >"
;
foreach
(
$xml
-> children()
as
$child
) {
if
(
$child
->
count
() > 0) {
// If any child of the current node exists
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 spaces
function
print_space (
$i
) {
for
(
$x
= 0;
$x
<
$i
* 3;
$x
++) {
echo
" "
;
}
}
?>
Output: Link: https://www.php.net/manual/en/simplexmlelement.getname.php