Thursday, October 9, 2025
HomeLanguagesPHP | XMLReader moveToElement() Function

PHP | XMLReader moveToElement() Function

The XMLReader::moveToElement() function is an inbuilt function in PHP which is used to move cursor to the parent element of current attribute. This function can be used to get the element having certain attributes by combining this with XMLReader::moveToAttribute() function.

Syntax:

bool XMLReader::moveToElement( void )

Parameters: This function doesn’t accepts any parameter.

Return Value: This function returns TRUE if successful and FALSE if it fails or not positioned on attribute when this method is called.

Below given programs illustrate the XMLReader::moveToElement() function in PHP:

Program 1: In this program, we will get the name of element having attribute “attrib”

Filename: data.xml




<?xml version="1.0" encoding="utf-8"?>
<div>
    <h1 attrib="value"> Foo Bar </h1>
</div>


Filename: 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 attribute with name attrib
$XMLReader->moveToAttribute("attrib");
  
// Move cursor to the element of attribute
$XMLReader->moveToElement();
  
// Output the name of element to browser
echo $XMLReader->name;
?>


Output:

h1

Program 2: In this program, we will get the name of all elements having attribute “attrib”.

Filename: data.xml




<?xml version="1.0" encoding="utf-8"?>
<div>
    <h1 attrib="value1"> Foo Bar </h1>
    <h2 attrib="value2"> Foo Bar </h2>
    <h3 other="value"> Foo Bar </h3>
    <h4 other="value"> Foo Bar </h4>
</div>


Filename: index.php




<?php
  
// Create a new XMLReader instance
$XMLReader = new XMLReader();
  
// Open the XML file
$XMLReader->open('data.xml');
  
// Iterate through the XML nodes
while ($XMLReader->read()) {
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
  
        // Get the element name if attribute
        // name is "attrib"
        if ($XMLReader->moveToAttribute("attrib")) {
  
            // Move cursor to the element of attribute
            $XMLReader->moveToElement();
  
            // Output the value to browser
            echo $XMLReader->name . "<br>";
        }
  
    }
}
?>


Output:

h1
h2

Reference: https://www.php.net/manual/en/xmlreader.movetoelement.php

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32345 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6714 POSTS0 COMMENTS
Nicole Veronica
11877 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11940 POSTS0 COMMENTS
Shaida Kate Naidoo
6834 POSTS0 COMMENTS
Ted Musemwa
7094 POSTS0 COMMENTS
Thapelo Manthata
6789 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS