Get node value as text using php + xpath

How can I just get the string value of an Xml node using xpath in PHP? I am RTM, but there are more complicated situations using foreach, I only want 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 am I doing:

$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 only value. Like a floating value.

+1
source share
2 answers

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 the array and extract its first element:

var_dump($EurToday[0]);


But this will give you an object SimpleXMLElement:

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


To get the float value that it contains, you must convert it to a float - for example, using floatval:

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


, :

float 17.4619


: , xpath false ( ), ( ), .

+3

XPath, w3schools.com

:

/bookstore/book/price/text()

text(), , , . PHP savexml() :

$EurToday = (float) $xmlToday->xpath("/ValCurs/Valute[@ID='47']/Value/savexml()");
+2

All Articles