PHP | XMLReader XML() Function

The XMLReader::XML() function is an inbuilt function in PHP which is used to set the data containing the XML to parse. XML() function serves the same purpose as open function but the only difference is former accepts XML as string while later accepts it as a separate .xml file.

Syntax:

bool XMLReader::XML( string $source, 
string $encoding, int $options )

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

  • $source: It specifies the string containing the XML to be parsed.
  • $encoding (Optional): It specifies the document encoding or NULL.
  • $options (Optional): It specifies the optional bitmask.

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

Exceptions: This function throws E_STRICT error when called statically.



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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new XMLReader instance
$XMLReader = new XMLReader();
  
$XML = "<?xml version=\"1.0\"?>
<div>
    <p> GeeksforGeeks </p>
</div>";
  
// Open the XML file
$XMLReader->XML($XML);
  
// Iterate through the XML nodes
while ($XMLReader->read()) {
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
  
        echo "We are at " . $XMLReader->name . "<br>";
  
    }
}
?>

chevron_right


Output:

We are at div
We are at p

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create a new XMLReader instance
$XMLReader = new XMLReader();
  
$XML = "<?xml version=\"1.0\"?>
<div>
    <p> GeeksforGeeks </p>
</div>";
  
// Open the XML file
$XMLReader->XML($XML);
  
// Read the nodes
$XMLReader->read();
  
// Read it as a string
$string = $XMLReader->readString();
   
// Output the string to the browser
echo $string;
?>

chevron_right


Output:

GeeksforGeeks

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