Friday, June 12, 2026
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

1 COMMENT

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS