使用 php + xpath 获取节点值作为文本 [英] obtain the node value as text with php + xpath
问题描述
如何在 PHP 中使用 xpath 获取 Xml 节点的字符串值?我 RTM 但有更复杂的情况,使用 foreach 我只想要我的节点文本.XML:
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>
我做什么:
$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::xpath
返回与 XPath 查询匹配的元素数组.
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]);
但这会给你一个 SimpleXMLElement
对象:
object(SimpleXMLElement)[2]
string '17.4619' (length=7)
要获取它包含的浮点值,您必须将其转换为浮点数——例如,使用 floatval
:
var_dump(floatval($EurToday[0]));
这让你得到你想要的:
Which gets you what you wanted :
float 17.4619
作为旁注:您应该检查 xpath
方法没有返回 false
(如果出现错误) 或空数组 (如果没有任何匹配的查询),在尝试处理其返回值之前.
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.
这篇关于使用 php + xpath 获取节点值作为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!