tags:

views:

257

answers:

2

How can I just obtain the string value of a Xml node using xpath in PHP? I RTFM 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.

+2  A: 

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]);


But this will get you a SimpleXMLElement object :

object(SimpleXMLElement)[2]
  string '17.4619' (length=7)


To get the float value it contains, you have to convert it to a float -- for instance, using floatval :

var_dump(floatval($EurToday[0]));


Which gets you what you wanted :

float 17.4619


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.

Pascal MARTIN
any way to specify it directly in Xpath à la `../Value/string()`?
serhio
Considering the manual says (quoting) *"Returns an array of SimpleXMLElement objects or FALSE in case of an error"*, I don't think that's possible.
Pascal MARTIN
merci bien, monsieur.
serhio
De rien :-) (et vous pouvez / tu peux laisser tomber le "monsieur" ^^ ) -- *you're welcome :-) (and you can drop the "sir" ^^ )*
Pascal MARTIN
D'accord, monsieur. Yes. Sir. :-)
serhio
A: 

XPath Examples, w3schools.com

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()");
esryl