PHP | XMLReader moveToNextAttribute() Function

The XMLReader::moveToNextAttribute() function is an inbuilt function in PHP which is used to move cursor to the next attribute if positioned on an attribute or moves to first attribute if positioned on an element. This function can also be used to check if attributes are there in an element or not.
Syntax:
bool XMLReader::moveToNextAttribute( void )
Parameters: This function doesn’t accept any parameters.
Return Value: This function returns TRUE on success or FALSE on failure.
Below examples illustrate the XMLReader::moveToNextAttribute() function in PHP:
Example 1:
- data.xml
<?xml version="1.0"encoding="utf-8"?><div>Â Â Â Â<h1> Foo Bar </h1></div> - index.php
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Open the XML file$XMLReader->open('data.xml');ÂÂ// Iterate through the XML nodes// to reach the h1 node$XMLReader->read();$XMLReader->read();$XMLReader->read();ÂÂ// Checking if attribute is there or notif($XMLReader->moveToNextAttribute()) {Â Â Â Âecho"Attribute is there";}else{Â Â Â Âecho"No, attributes.";}?> - Output:
No, attributes.
Example 2:
- data.xml
<?xml version="1.0"encoding="utf-8"?><div>Â Â Â Â<h1 attrib1="value1"Â Â Â Â Â Â Â Âattrib2="value2"ÂÂ Â Â Â Â Â Â Âattrib3="value">Â Â Â Â ÂFoo BarÂÂ Â Â Â</h1></div> - index.php
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Open the XML file$XMLReader->open('data.xml');ÂÂ// Iterate through the XML nodes// to reach the h1 node$XMLReader->read();$XMLReader->read();$XMLReader->read();ÂÂ// Move to first attribute$XMLReader->moveToFirstAttribute();ÂÂ// Print name of elementecho"Before:<br> We are currently "Â Â Â Â Â Â."at: $XMLReader->name<br>";ÂÂ// Move to next attribute$XMLReader->moveToNextAttribute();ÂÂ// Print name of elementecho"After:<br> We are currently "Â Â Â Â Â Â."at: $XMLReader->name";?> - Output:
Before: We are currently at: attrib1 After: We are currently at: attrib2
Reference: https://www.php.net/manual/en/xmlreader.movetonextattribute.php



