强制 SimpleXML 对象为字符串,而不考虑上下文 [英] Forcing a SimpleXML Object to a string, regardless of context

查看:22
本文介绍了强制 SimpleXML 对象为字符串,而不考虑上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些这样的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆