略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: SimpleXMLElement::__toString

2024-11-14

SimpleXMLElement::__toString

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

SimpleXMLElement::__toStringReturns the string content

说明

public SimpleXMLElement::__toString(): string

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 noteadd a note

User Contributed Notes 3 notes

up
10
mmj at example dot net
4 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
9
Patanjali
6 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
-24
Patanjali
6 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.

官方地址:https://www.php.net/manual/en/simplexmlelement.tostring.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3