__toString() is not intended to be called directly.Instead, it defines what is returned when the object is cast to string, either explicitly with:(string)$elementOr implicitly, when used in certain contexts which would cause a conversion to string.
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SimpleXMLElement::__toString — Devuelve el contenido como string
Devuelve el contenido de texto almacenado directamente en el elemento. No devuelve el contenido de texto almacenado en los elementos hijos.
Esta función no contiene ningún parámetro.
Devuelve el contenido como string, o un string vacío en caso de error.
Ejemplo #1 Obtener el contenido como string
<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>
El ejemplo anterior mostrará :
1 3
__toString() is not intended to be called directly.Instead, it defines what is returned when the object is cast to string, either explicitly with:(string)$elementOr implicitly, when used in certain contexts which would cause a conversion to string.
For those for whom it may not be immediately obvious from the example, the echo is what is forcing __toString() to be used.
However, to assign the text of a node (but not its children) to a variable:
$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');
$Text = $XML->__toString();
is effectively:
$Text = 'Hello.'; // The <span>s are ignored.
Either of:
$Text = $XML->span->__toString();
$Text = $XML->span[0]->__toString();
is effectively:
$Text = ' world'; // Only the first <span> is used.
$Text = $XML->span[1]->__toString();
is effectively:
$Text = ' Good day!'; // Only the second <span> is used.