simplexml 无需类型转换即可获取节点值
有没有办法从 simplexml
对象获取节点值而不转换它?
$amount = (int)$item->amount;
在我看来这不是很漂亮,我正在寻找一种更干净的方法,但到目前为止没有找到任何东西!
//wouldn't this be nice?
$amount = $item->amount->getValue();
提前致谢。
Is there any way to get a node value from a simplexml
object without casting it?
$amount = (int)$item->amount;
This is not very beautiful in my opinion, I'm searching for a cleaner way but did not find anything so far!
//wouldn't this be nice?
$amount = $item->amount->getValue();
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。
SimpleXml
仅公开非常有限的 API 来处理节点。它的隐式 API 被视为一项功能。如果您需要对节点进行更多控制,请使用DOM
:dom_import_simplexml
函数会将节点从SimpleXmlElement
转换为DOMElement
,因此您仍然以某种方式在幕后进行转换。不过,从DOMElement
获取内容时,您不再需要显式进行类型转换。旁注:就个人而言,我发现
DOM
优于SimpleXml
,并且我建议不要使用SimpleXml
但 <立即代码>DOM。如果您想熟悉它,请查看我之前关于使用 DOM 的一些答案。No.
SimpleXml
only exposes a very limited API to work with nodes. It's implicit API is considered a feature. If you need more control over the nodes, useDOM
:The
dom_import_simplexml
function will convert the node from aSimpleXmlElement
to aDOMElement
, so you are still casting behind the scenes somehow. You no longer need to typecast explicitly though, when fetching the content from theDOMElement
.On a sidenote: personally, I find
DOM
superior toSimpleXml
and I'd suggest not to useSimpleXml
butDOM
right away. If you want to familiarize yourself with it, have a look at some of my previous answers about using DOM.无需进行类型转换即可获取节点的值?当然可以! :3
现在您只需使用
simplexml_load_string()
的第二个参数即可获得更简单的 XML 元素!但更严重的是,节点就是节点。如果您需要将节点的值用作字符串、整数等,那么无论您是否亲自执行,都将在某一点上涉及类型转换。
Getting the value of a node without having to typecast it? Sure thing! :3
Now you just have to use
simplexml_load_string()
's second parameter to get even simpler XML elements!More seriously though, a node is a node. If you need to use the value of a node as a string, integer and what not, it will involve typecasting at one point or another, whether you do it personally or not.
但这是最安全的:)。您可以创建一个函数来递归地转换数组中的对象。早在我第一次开始在 PHP 中使用 XML 时,我就记得得出这样的结论:类型转换是最好的方法:)
But it is the safest :). You could create a function to recursively convert the object in an array. Way back when I first starte working with XML in PHP, I remember reaching the conclusion that type casting is just the best method :)
那么xpath方式呢?
What about xpath way?