迭代XML元素并将元素推送到数组中
16lz
2021-01-22
I have a simple XML document containing two city id's.
我有一个包含两个城市ID的简单XML文档。
<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
<city>
<id>London</id>
</city>
<city>
<id>New York</id>
</city>
</config>
When iterating over the XML I can only pick up the first city id, e.g. London.
在迭代XML时,我只能获取第一个城市ID,例如伦敦。
<?php
$configFile = 'cityConfig.xml';
function getCityId($configFile) {
$xml = new SimpleXmlElement(file_get_contents("cityConfig.xml"));
$cities = array();
foreach ($xml->city->id as $cityId) {
$cityId = (string) $cityId;
array_push($cities, $cityId);
}
return $cities;
}
print_r(getCityId($configFile));
?>
<?php
The output from the above:
以上输出:
// Array ( [0] => London )
I'm casting $cityId
into a string to be used elsewhere in my website.
我正在将$ cityId转换为一个字符串,以便在我的网站的其他地方使用。
Any ideas where I'm going wrong?
我出错的任何想法?
Thanks in advance.
提前致谢。
1 个解决方案
#1
1
foreach ($xml->city->id as $cityId)
Should be:
应该:
foreach ($xml->city as $city) {
$cityId = $city->id;
...
}