serhio
serhio

Reputation: 28586

obtain the node value as text with php + xpath

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

Answers (2)

user137621
user137621

Reputation:

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

Upvotes: 2

Pascal MARTIN
Pascal MARTIN

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

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`][2] :
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.

Upvotes: 3

Related Questions