PHP | XMLReader moveToElement() Function
Last Updated :
26 Mar, 2020
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
html
<?xml version="1.0" encoding="utf-8"?>
<div>
<h1 attrib="value"> Foo Bar </h1>
</div>
Filename: index.php
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
html
<?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
<?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
Explore
Basics
Array
OOPs & Interfaces
MySQL Database
PHP Advance