SunshinePHP 2020

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7)

SimpleXMLElement::__toString文字列で要素の内容を返す

説明

public SimpleXMLElement::__toString ( void ) : string

この要素に直接入っているテキストの内容を返します。 この要素の子要素の内部にあるテキストの内容を返してはいけません。

パラメータ

この関数にはパラメータはありません。

返り値

成功したときは、テキストの内容を文字列で返します。 失敗したときは空文字列を返します。

例1 文字列で内容を取得する

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

上の例の出力は以下となります。

1 3

参考

add a note add a note

User Contributed Notes 3 notes

up
10
Patanjali
3 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.
up
1
mmj at example dot net
2 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
-18
Patanjali
3 years ago
For those for whom it may not be immediately obvious from the example, 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>');

Either:
$Text = $XML;
$Text = $XML->__String();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span;
$Text = $XML->span[0];

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1];

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.
To Top