simplexml get node value without typecasting

醉酒当歌 提交于 2019-12-10 17:05:09

问题


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.


回答1:


Getting the value of a node without having to typecast it? Sure thing! :3

class SimplerXMLElement extends SimpleXMLElement
{
    public function getValue()
    {
        return (string) $this;
    }
}

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.




回答2:


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, use DOM:

$sxe = simplexml_load_string(
    '<root><item><amount>10</amount></item></root>'
);
$node = dom_import_simplexml($sxe->item->amount);
var_dump($node->nodeValue); // string(2) "10"

The dom_import_simplexml function will convert the node from a SimpleXmlElement to a DOMElement, so you are still casting behind the scenes somehow. You no longer need to typecast explicitly though, when fetching the content from the DOMElement.

On a sidenote: personally, I find DOM superior to SimpleXml and I'd suggest not to use SimpleXml but DOM right away. If you want to familiarize yourself with it, have a look at some of my previous answers about using DOM.




回答3:


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 :)




回答4:


What about xpath way?

$amount = $item->amount->xpath('text()');


来源:https://stackoverflow.com/questions/4722653/simplexml-get-node-value-without-typecasting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!