PHP 7.0.6 Released

SimpleXMLElement::__toString

(バージョン情報なし。おそらく SVN 版にしか存在しないでしょう)

SimpleXMLElement::__toStringReturns the string content

説明

public string SimpleXMLElement::__toString ( void )

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

パラメータ

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

返り値

Returns the string content on success or an empty string on failure.

例1 Get string content

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

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

1 3

参考

add a note add a note

User Contributed Notes 2 notes

up
1
Patanjali
1 month 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
-2
Patanjali
1 month 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