无论上下文如何,都将SimpleXML对象强制为字符串 [英] Forcing a SimpleXML Object to a string, regardless of context
问题描述
假设我有一些这样的XML
Let's say I have some XML like this
<channel>
<item>
<title>This is title 1</title>
</item>
</channel>
下面的代码实现了我想要的功能,它将标题输出为字符串
The code below does what I want in that it outputs the title as a string
$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;
这是我的问题.下面的代码在该上下文中并未将标题视为字符串,因此我最终在数组中使用了SimpleXML对象而不是字符串.
Here's my problem. The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.
$foo = array( $xml->channel->item->title );
我一直在这样解决它
$foo = array( sprintf("%s",$xml->channel->item->title) );
但这看起来很丑.
无论上下文如何,将SimpleXML对象强制为字符串的最佳方法是什么?
推荐答案
将SimpleXMLObject类型转换为字符串:
$foo = array( (string) $xml->channel->item->title );
上面的代码在内部调用SimpleXMLObject上的__toString()
.此方法不是公开可用的,因为它会干扰SimpleXMLObject的映射方案,但仍可以按上述方式调用.
The above code internally calls __toString()
on the SimpleXMLObject. This method is not publicly available, as it interferes with the mapping scheme of the SimpleXMLObject, but it can still be invoked in the above manner.
这篇关于无论上下文如何,都将SimpleXML对象强制为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!