Getting Actual Value from PHP Simplexml Node

Getting actual value from PHP SimpleXML node

Cast as whatever type you want (and makes sense...). By concatenating, you're implicitly casting to string, so

$value = (string) $xml->someNode->innerNode;

SimpleXML get node value

$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->parent[0]->child1;

Get attribute value in SimpleXML object by element and another attribute value

You can use SimpleXML's xpath method to return an attribute of a node based on the value of another attribute:

$sxml = simplexml_load_string($xml);

$rate = (float) $sxml->xpath('./currencies/currency[@id="EUR"]/@rate')[0];

echo $rate;

Note that the method will always return an array, so we need to ask for the first element, and then cast the value to a float.

See https://eval.in/957883 for a full example

get node and subnode text value in simpleXML

$book->title is of type SimpleXMLElement. You could pass that to dom_import_simplexml and get the nodeValue:

$sxml = simplexml_load_string($xml);
foreach($sxml->xpath('//book') as $book){
echo dom_import_simplexml($book->title)->nodeValue . "<br>";
// or use
// echo strip_tags($book->title->asXml()) . "<br>";
}

That will give you:

I love apple pie
I love chocolate

Demo

PHP SimpleXML - can't get a single node value, am I crazy?

SimpleXML turns everything into SimpleXMLElement objects. Just cast it to a string (or whatever):

(string) $xmlStrShipping->Orders[0]->Order->number;

or if you invoke it in a string context it will work as well because SimpleXMLElement has the magic __toString() method implemented:

echo $xmlStrShipping->Orders[0]->Order->number;

Help! get node value via php simplexml !

Replace your whole loop with:

foreach ($result as $node) {
$arr[] = (string)$node;
}

or even:

$result = array_map('strval', $result);


Related Topics



Leave a reply



Submit