gpt4 book ai didi

Php 从 xml 节点获取特定值(调用节点名称)

转载 作者:数据小太阳 更新时间:2023-10-29 02:30:51 24 4
gpt4 key购买 nike

XML

<CRates>
<Currencies>
<Currency>
<ID>AED</ID>
<Units>1</Units>
<Rate>0.17200000</Rate>
</Currency>
<Currency>
<ID>ATS</ID>
<Units>1</Units>
<Rate>0.04102750</Rate>
</Currency>
</Currencies>
</CRates>

想得到例如Rate值在哪里 ID是ATS

目前只能这样获取

$xmlDoc = simplexml_load_file('__joomla.xml');
echo $xmlDoc->Currencies->Currency[1]->Rate;

<ID>ATS</ID>在第二个<Currency>之内, 所以 Currency[1]

当然echo $xmlDoc->Currencies->Currency[ATS]->Rate;不起作用。但是有什么简单的方法可以让它发挥作用吗?

似乎需要使用 foreach如果 <ID>,则在 foreach 内部== ATS,回显<Rate>

最佳答案

试试这个:

// This way should work for all versions of PHP
$rate = false;
foreach ($xmlDoc->Currencies->Currency as $currency)
{
if ((string)$currency->ID == 'ATS')
{
$rate = (string)$currency->Rate;
break;
}
}

// This way should work for newer versions of PHP only, I personally think that anonymous functions like this add to the readability which is why I included both options
$rate = call_user_func(function() use ($xmlDoc) {
foreach ($xmlDoc->Currencies->Currency as $currency)
{
if ((string)$currency->ID == 'ATS')
return (string)$currency->Rate;
}
return false;
});

// Using false to signify failure is the standard in PHP
if ($rate !== false)
echo 'The rate is: ',$rate;
else
echo 'Rate not found';

您可能不需要转换为字符串,但我相信如果您不这样做,您最终会得到 SimpleXMLElement 对象(或具有类似名称的对象)而不是字符串。

关于Php 从 xml 节点获取特定值(调用节点名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18002464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com