How can I just obtain the string value of a Xml node using xpath in PHP?
I RTM but there is more complicated situations, using foreach I want just my node text.
XML:
<ValCurs Date="00.00.0000" name="Official exchange rate">
<Valute ID="47">
<NumCode>978</NumCode>
<CharCode>EUR</CharCode>
<Nominal>1</Nominal>
<Name>Euro</Name>
<Value>17.4619</Value>
</Valute>
</ValCurs>
what I do:
$xmlToday = simplexml_load_file($urlToday);
$EurToday = $xmlToday->xpath("/ValCurs/Valute[@ID='47']/Value");
$EurToday = array(1) { [0]=> object(SimpleXMLElement)#3 (1)
{ [0]=> string(7) "17.4619" } }
I need the value only. As a floating value.
SimpleXMLElement::xpathreturns an array of elements matching the XPath query.This means that if you have only one element, you still have to work with an array, and extract its first element :
But this will get you a `SimpleXMLElement` object :
To get the float value it contains, you have to convert it to a float — for instance, using [`floatval`][2] :
Which gets you what you wanted :
As a sidenote : you should check that the `xpath` method didn’t return either `false` *(in case of an error)* or an empty array *(if nothing matched the query)*, before trying to work with its return value.