Monday, December 22, 2025
HomeLanguagesPHP | XMLReader readString() Function

PHP | XMLReader readString() Function

The XMLReader::readString() function is an inbuilt function in PHP which is used to read the contents of the current node as a string. Difference between readString() and getInnerXml() is that the former doesn’t includes the markup but only the content for subnodes.

Syntax:

string XMLReader::readString( void )

Parameters: This function doesn’t accept any parameter.

Return Value: This function returns the content of the current node as a string or empty string on failure.

Below examples illustrate the XMLReader::readString() function in PHP:

Example 1: In this program, we will read the value of an element without sub-nodes.

  • data.xml




    <?xml version="1.0" encoding="utf-8"?>
    <div>
        <h1>neveropen</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 element
    $XMLReader->read();
    $XMLReader->read();
    $XMLReader->read();
      
    // Print the XML content
    echo "The text inside is:" 
      . $XMLReader->readString();
    ?>

    
    
  • Output:
    The text inside is: neveropen

Example : In this program, we will read the value of an element with sub-nodes.

  • data.xml




    <?xml version="1.0" encoding="utf-8"?>
    <div>
        <h1>Hello World 
           <sub>G4G</sub>
        </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 element
    $XMLReader->read();
    $XMLReader->read();
    $XMLReader->read();
      
    // Print the XML content
    echo "The text inside is:" 
      . $XMLReader->readString();
    ?>

    
    
  • Output:
    The text inside is: Hello World G4G

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

RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS