Reputation: 28586
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.
Upvotes: 1
Views: 4515
Reputation:
See section: Select all the prices
/bookstore/book/price/text()
text() seems to get what you are looking for. The equivalent in PHP seems to be savexml() Hence:
$EurToday = (float) $xmlToday->xpath("/ValCurs/Valute[@ID='47']/Value/savexml()");
Upvotes: 2
Reputation: 400932
SimpleXMLElement::xpath
returns 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 :
var_dump($EurToday[0]);
object(SimpleXMLElement)[2]
string '17.4619' (length=7)
var_dump(floatval($EurToday[0]));
float 17.4619
Upvotes: 3