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


Trying to extract elements from XML and place into an Array

我创建了一个简单的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); 
?>

CCD_ 2表明值正在被添加到数组中。

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] . '.';

你知道我哪里错了吗?

提前谢谢。

事实是,在SimpleXMLElement对象中,所有数据都表示为一个对象,包括属性(事实上,正如var_dump所建议的那样)。因此,您可以通过强制转换这些对象来获得字符串,因为我认为它们实现了_toString()方法。尝试:

$cityId = (string) $xml->city[0]->id;

它应该起作用。