PHP | SimpleXMLElement __toString() Function

The XMLReader::__toString() function is an inbuilt function in PHP which is used to get the text content that is directly in current element. This function does not return text content that is inside this element’s children.

Syntax:

void XMLReader::__toString( void )

Parameters: This function doesn’t accept any parameters.

Return Value: This function returns a string content on success or an empty string on failure.

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



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create the XML
$xmlstr = <<<XML
<?xml version='1.0'?>
<library>
  GeeksforGeeks
</library>
XML;
  
// Create a new SimpleXMLElement
$SXE = new SimpleXMLElement($xmlstr);
  
// Get the content
$string = $SXE->__toString();
echo $string;
?>

chevron_right


Output:

GeeksforGeeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Create the XML
$xmlstr = <<<XML
<?xml version='1.0'?>
<div>
  <sub>
  This text should not be visible
  </sub>
</div>
XML;
  
// Create a new SimpleXMLElement
$SXE = new SimpleXMLElement($xmlstr);
  
// Add the attribute
$string = $SXE->__toString();
echo $string;
?>

chevron_right


Output:

// Empty string because text content is in a childern node not current node.

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