Simplexml gets node value without typing

Is there a way to get the node value from a simplexml object without casting it?

 $amount = (int)$item->amount; 

This is not very beautiful, in my opinion, I am looking for a cleaner way, but I did not find anything!

 //wouldn't this be nice? $amount = $item->amount->getValue(); 

Thanks in advance.

+4
source share
4 answers

Getting a node value without having to match it? Of course !: 3

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

Now you need to use the second parameter simplexml_load_string() to get even simpler XML elements!

More seriously, although node is node. If you need to use the value of node as a string, an integer and what is not, it will include the identity at some point, regardless of whether you do it personally or not.

+1
source

No. SimpleXml provides only a very limited API for working with nodes. Implicit API is considered a feature. If you need extra control over nodes, use the 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 converts the node from SimpleXmlElement to DOMElement , so you are still casting overs. You no longer need to explicitly specify when displaying content from DOMElement .

On the side: I personally find the DOM above SimpleXml , and I suggest not using SimpleXml , but the DOM right away. If you want to familiarize yourself with it, check out some of my previous answers about using the DOM .

+4
source

But this is the safest :). You can create a function to recursively convert an object to an array. Let's go back when I first started working with XML in PHP, I remember that I came to the conclusion that type casting is the best method :)

0
source

What about the xpath?

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

Source: https://habr.com/ru/post/1335965/


All Articles