PHP XMLReader::getAttributeNo() 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. XMLReader extension is used to read/retrieve the contents of an XML document i.e. using the methods of the XMLReader class you can read each node of an XML document.
The XMLReader::getAttributeNo() function of the XMLReader class accepts an integer value representing the index of an attribute and returns its value.
Syntax
XMLReader::getAttributeNo($index);
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
index(Mandatory) This is an integer value representing the index of an attribute. |
Return Values
This function returns a string value representing the value of the specified attribute. If the specified attribute does not exist this function returns NULL.
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 XMLReader::getAttributeNo() function −
data.xml
<Employee> <Name id = "name">Krishna</Name> <Age id = "age">22</Age> <City id = "city">Hyderabad</City> <Phone id = "phone">Hyderabad</Phone> </Employee>
sample.php
<?php
//Creating an XMLReader
$reader = new XMLReader();
//Opening a reader
$reader->open('trail.xml');
//reading the contents of the XML file
while($reader->read()){
if ($reader->nodeType == XMLREADER::ELEMENT) {
$res = $reader->getAttributeNo(0);
print($res."\n");
}
}
//Closing the reader
$reader->close();
?>
This will produce following result −
name age city phone
Example
Following is another example of this function −
test.xml
<data> <name att = 'test_attribute'>Raju</name> <age>32</age> <phone>9848022338</phone> <city>Hyderabad</city> </data>
sample.php
<?php
//Creating an XMLReader
$reader = new XMLReader();
//Opening a reader
$reader->open("test.xml");
//Reading the contents
$reader->next();
$reader->read();
$reader->next();
print($reader->getAttributeNo(0)."\n");
//Closing the reader
$reader->close();
?>
This will produce following result −
test_attribute
Example
<?php
//Creating an XMLReader
$reader = new XMLReader();
$data = "<data>
<name att = 'test_attribute'>Raju</name>
<age>32</age>
<phone>9848022338</phone>
<city>Hyderabad</city>
</data>";
//Opening a reader
$reader->xml($data);
//Reading the contents
$reader->next();
$reader->read();
$reader->next();
print($reader->getAttributeNo(0)."\n");
//Closing the reader
$reader->close();
?>
This will produce following result −
test_attribute