Xml是这样的:
<CRates>
<Date>20010323</Date>
<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>
Php是这样的:
$currencies = simplexml_load_file('__joomla.xml');
/**/
$cdate=$currency->Date;
echo "<time>". $date. "</time><br>";
foreach ($currencies as $currency):
$id=$currency->ID;
$units=$currency->Units;
$rate=$currency->Rate;
echo
"
<div class='id'>". $id. "</div>
<div class='units'>". $units. "</div>
<div class='rate'>". $rate. "</div>
";
endforeach;
如果删除<CRates> <Date>20010323</Date>
并删除结尾</CRates>
,则一切正常。
但未删除,不显示任何内容。
请建议需要纠正的内容。
答案 0 :(得分:4)
原因是因为您正在访问$currencies
,就像它的根元素一样。您可以使用$xmlDoc->currencies
加载文件和参考货币,它应该可以使用。请尝试以下方法:
$xmlDoc = simplexml_load_file('__joomla.xml');
/**/
$cdate=$xmlDoc->Date;
echo "<time>". $cdate. "</time><br>";
foreach ($xmlDoc->Currencies->Currency as $currency):
$id=$currency->ID;
$units=$currency->Units;
$rate=$currency->Rate;
echo
"
<div class='id'>". $id. "</div>
<div class='units'>". $units. "</div>
<div class='rate'>". $rate. "</div>
";
endforeach;
更新:将$xmlDoc->Currencies
更新为$xmlDoc->Currencies->Currency
,因为我们想要循环通过货币的子女。
答案 1 :(得分:1)
试试这个:
$currencies = simplexml_load_file('__joomla.xml');
/**/
$cdate = $currencies->Date;
echo "<time>". $date. "</time><br>";
foreach ($currencies->CRates->Currencies->Currency as $currency):
$id = $currency->ID;
$units = $currency->Units;
$rate = $currency->Rate;
echo
"
<div class='id'>". $id. "</div>
<div class='units'>". $units. "</div>
<div class='rate'>". $rate. "</div>
";
endforeach;
答案 2 :(得分:1)
您需要使用->children()
来迭代Currencies
$crates = simplexml_load_file('__joomla.xml');
/**/
$cdate = $crates->Date;
echo "<time>". $cdate. "</time><br>";
$currencies = $crates->Currencies->children();
foreach ($currencies as $currency):
$id = $currency->ID;
$units = $currency->Units;
$rate = $currency->Rate;
echo
"
<div class='id'>". $id. "</div>
<div class='units'>". $units. "</div>
<div class='rate'>". $rate. "</div>
";
endforeach;
答案 3 :(得分:1)
这很好用: -
$xml='<CRates>
<Date>20010323</Date>
<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>';
$xml1 = simplexml_load_string($xml);
//$xml hold the object iterate through as per requirement
echo '<pre>';
var_dump($xml1);