PHP | XMLReader read() Function

The XMLReader::read() function is an inbuilt function in PHP which is used to move to next node in document. Thus this function is used to traverse through the XML document.

Syntax:

bool XMLReader::read( void )

Parameters: This function doesn’t accepts any parameter.



Return Value: This function returns TRUE on success or FALSE on failure.

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

Program 1: In this program, we will get the value of a element after traversing the file data.xml

Filename: data.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<div1>
    <h1> GeeksforGeeks </h1>
</div1>

chevron_right


Filename: index.php

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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 element's text 
// (Only four times)
$XMLReader->read();
$XMLReader->read();
$XMLReader->read();
$XMLReader->read();
  
// Print the value of element
echo "The text inside is: "
    . "$XMLReader->value<br>";
?>

chevron_right


Output:

GeeksforGeeks

Program 2: In this program, we will get the name of an element after traversing to it.

Filename: data.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<div1>
    <h1> GeeksforGeeks </h1>
</div1>

chevron_right


Filename: index.php

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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 element
// (only three times)
$XMLReader->read();
$XMLReader->read();
$XMLReader->read();
  
// Print name of element
echo "The name of element is: "
     . "$XMLReader->name<br>";
?>

chevron_right


Output:

The name of element is: h1

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




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.