【问题标题】:Iterate over XML element and push element into array遍历 XML 元素并将元素推送到数组中
【发布时间】:2012-02-21 08:21:12
【问题描述】:

我有一个包含两个城市 ID 的简单 XML 文档。

<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
    <city>
        <id>London</id>
    </city>
    <city>
        <id>New York</id>
    </city>
</config>

在遍历 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

上面的输出:

// Array ( [0] => London )

我将$cityId 转换为一个字符串,以便在我网站的其他地方使用。

任何想法我哪里出错了?

提前致谢。

【问题讨论】:

  • 我想你应该遍历$xml-&gt;city as $city,然后使用$city-&gt;id

标签: php xml iterator


【解决方案1】:
foreach ($xml->city->id as $cityId)

应该是:

foreach ($xml->city as $city) {
    $cityId = $city->id;
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2013-01-21
    相关资源
    最近更新 更多