Thursday, October 9, 2025
HomeLanguagesPHP | SimpleXMLElement __toString() Function

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:  

PHP




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


Output: 

neveropen

Example 2: 

PHP




<?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;
?>


Output: 

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

Reference: https://www.php.net/manual/en/simplexmlelement.tostring.php
 

RELATED ARTICLES

Most Popular

Dominic
32346 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6714 POSTS0 COMMENTS
Nicole Veronica
11877 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11940 POSTS0 COMMENTS
Shaida Kate Naidoo
6835 POSTS0 COMMENTS
Ted Musemwa
7094 POSTS0 COMMENTS
Thapelo Manthata
6789 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS