我创建了一个简单的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] . '.';
有什么想法我做错了吗?
提前致谢。
echo getCityConfig(..)
,在 PHP 中你不能以这种方式打印出一个数组。你必须使用print_r
或var_dump
。事实上,数组不是字符串,因此输出整个数组没有意义。 - lorenzo-s$pageIntroductionContent
。当我尝试调用index 0
时,我得到未定义函数的错误,并且如果我使用require cityConfig.php
,则会出现Warning: file_get_contents(cityConfig.xml) [function.file-get-contents]: failed to open stream
的错误。 - keenProgrammercityConfig.xml
。请重新检查文件路径。 - lorenzo-s