PHP - SimpleXMLIterator::key() Function
Definition and Usage
XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. The SimpleXMLIterator is used to iterate all the nodes of an XML document.
The SimpleXMLIterator::key() function retrieves and returns the tag name of the current element.
Syntax
SimpleXMLIterator::key(void);
Parameters
This function doesnt accept any parameters.
Return Values
This function returns a string value representing the tag name of the current element or, the boolean value FALSE in case of issues.
PHP Version
This function was first introduced in PHP Version 5 and works in all the later versions.
Example
Following example demonstrates the usage of the SimpleXMLIterator:: key() function.
<html>
<head>
<body>
<?php
$doc = new DOMDocument;
$data = "<?xml version = '1.0' encoding = 'UTF-8'?>
<Employee>
<Name>Raju</Name>
<Age>25</Age>
<Salary>2000</Salary>
</Employee>";
//Creating the SimpleXMLIterator
$xmlIterator = new SimpleXMLIterator($data);
$res = key($xmlIterator);
print($res);
?>
</body>
</head>
</html>
This will produce following result −
Name
Example
In the following example we are trying to retrieve the keys of all the elements of an XML document −
Data.xml:
<Tutorial> <Name>JavaFX</Name> <Pages>535</Pages> <Author>Krishna</Author> <Version>11</Version> </Tutorial>
sample.html
<html>
<head>
<body>
<?php
$doc = new DOMDocument;
//Creating the SimpleXMLIterator
$xmlIterator = new SimpleXMLIterator("data.xml", 0, TRUE, "", FALSE);
for($xmlIterator->rewind();
$xmlIterator->valid();
$xmlIterator->next() ){
print($xmlIterator->key());
echo "<br><br>";
}
?>
</body>
</head>
</html>
This will produce the following output −
Name Pages Author Version