Open In App

PHP | XMLReader moveToNextAttribute() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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 = new XMLReader();
      
    // 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 not
    if ($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 = new XMLReader();
      
    // 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 element
    echo "Before:<br> We are currently "
          . "at: $XMLReader->name<br>";
      
    // Move to next attribute
    $XMLReader->moveToNextAttribute();
      
    // Print name of element
    echo "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



Last Updated : 18 Mar, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads