开发者

simplexml get node value without typecasting

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(开发者_JS百科);

Thanks in advance.


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.


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.


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


What about xpath way?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜