尝试从XML中提取元素并放入数组

3

我创建了一个简单的XML文档,用于保存多个城市的信息。

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

我正在尝试提取城市元素并将它们放入一个数组中。到目前为止,我的代码如下,当我调用该函数时,输出仅为Array

<?php
$configFile = 'cityConfig.xml';

function getCityConfig($configFile) {

    $xml = new SimpleXmlElement(file_get_contents("cityConfig.xml"));

    $cities = array();

    $cityId = $xml->city[0]->id;
    array_push($cities, $cityId);
    $cityId = $xml->city[1]->id;
    array_push($cities, $cityId);

    //var_dump($cities); 

    return $cities;
}

//print_r(getCityConfig($configFile)); 
echo getCityConfig($configFile); 

?>
var_dump 提示数组中已添加值。
array(2) { [0]=> object(SimpleXMLElement)#2 (1) { [0]=> string(6) "London" } [1]=> object(SimpleXMLElement)#4 (1) { [0]=> string(8) "New York" } } Array

我想要实现类似以下这样的功能。

$cities = array(
   'London',
    'New York',
    'Paris'
);

数组索引在我的index.php文件中被调用以显示内容。
$pageIntroductionContent = 'The following page brings twin cities together. Here you will find background information on  ' . $cities[0] . ', ' . $cities[1] . ' and ' . $cities[2] . '.';

有什么想法我做错了吗?
提前致谢。
1个回答

1
事实上,在SimpleXMLElement对象中,所有数据都表示为一个对象,包括属性(正如您的var_dump所示)。因此,您可以通过将这些对象强制转换为字符串来获取字符串,因为它们实现了一个_toString()方法。请尝试:
$cityId = (string) $xml->city[0]->id;

应该可以工作。


谢谢,我漏掉了那个。关于打印数组内容,你有什么想法? - keenProgrammer
1
你的代码没问题,你只需要按照我说的将字符串转换。如果你是在谈论 echo getCityConfig(..),在 PHP 中你不能以这种方式打印出一个数组。你必须使用 print_rvar_dump。事实上,数组不是字符串,因此输出整个数组没有意义。 - lorenzo-s
谢谢你解决了这个问题。最后一个问题是访问我index.php脚本中的数组索引$pageIntroductionContent。当我尝试调用index 0时,我得到未定义函数的错误,并且如果我使用require cityConfig.php,则会出现Warning: file_get_contents(cityConfig.xml) [function.file-get-contents]: failed to open stream的错误。 - keenProgrammer
所以,您无法访问 cityConfig.xml。请重新检查文件路径。 - lorenzo-s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接