PHP 8.4.0 RC4 available for testing

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::__toStringRetourne le contenu sous forme de chaine

Description

public SimpleXMLElement::__toString(): string

Retourne le contenu texte stocké directement dans l'élément. Ne retourne pas le contenu texte stocké dans les éléments enfants.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne le contenu sous forme de chaîne de caractères, ou retourne une chaine vide en cas d'erreur.

Exemples

Exemple #1 Récupérer le contenu chaine

<?php
$xml
= new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo
$xml;
?>

L'exemple ci-dessus va afficher :

1 3

Voir aussi

add a note

User Contributed Notes 2 notes

up
16
mmj at example dot net
7 years ago
__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)$element

Or implicitly, when used in certain contexts which would cause a conversion to string.
up
11
Patanjali
8 years ago
[Someone remove that other Patanjali's note, because it has errors! :-(]

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.
To Top