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

PHP | XMLReader open() Function

The XMLReader::open() function is an inbuilt function in PHP which is used to set the URI containing the XML document to be parsed. In simple words, this function is used to open the XML file which needs to be worked upon.

Syntax:

bool XMLReader::open( string $URI, string $encoding, int $options )

Parameters: This function accept three parameters as mentioned above and described below:

  • $URI: It specifies the URI pointing to the document.
  • $encoding (Optional): It specifies the document encoding or NULL.
  • $options (Optional): It specifies the bitmask.

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

Exceptions: This function throws an E_STRICT error, if called statically.

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

Example 1:

  • data.xml




    <?xml version="1.0" encoding="utf-8"?>
    <body>
        <h1 attrib="value"> Hello </h1>
    </body>

    
    
  • index.php




    <?php
      
    // Create a new XMLReader instance
    $XMLReader = new XMLReader();
      
    // Load the XML file
    $XMLReader->open('data.xml');
      
    // Iterate through the XML
    while ($XMLReader->read()) {
        if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
      
            // Get the value of first attribute
            $value = $XMLReader->getAttributeNo(0);
      
            // Output the value to browser
            echo $value . "<br>";
        }
    }
    ?>

    
    
  • Output:
    value

Program 2:

  • data.xml




    <?xml version="1.0" encoding="utf-8"?>
    <body>
        <h1> neveropen </h1>
    </body>

    
    
  • index.php




    <?php
      
    // Create a new XMLReader instance
    $XMLReader = new XMLReader();
      
    // Load the XML file
    $XMLReader->open('data.xml');
      
    // Move to the first node
    $XMLReader->read();
      
    // Read it as a string
    $string = $XMLReader->readString();
      
    // Output the string to the browser
    echo $string;
    ?>

    
    
  • Output:
    neveropen

Reference: https://www.php.net/manual/en/xmlreader.open.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