【问题标题】:Trying to extract elements from XML and place into an Array尝试从 XML 中提取元素并放入数组
【发布时间】:2012-03-11 04:02:21
【问题描述】:

我创建了一个简单的 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] . '.';

任何想法我哪里出错了?

提前致谢。

【问题讨论】:

    标签: php xml arrays


    【解决方案1】:

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

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

    它应该可以工作。

    【讨论】:

    • 谢谢,我错过了那个。关于打印出数组上的内容,我有什么想法吗?
    • 你的代码没问题,你只需要像我说的那样转换字符串。如果你在谈论echo getCityConfig(..),在 PHP 中你不能以这种方式打印出一个数组。您必须使用print_rvar_dump。其实数组不是字符串,所以输出整个数组是没有意义的。
    • 感谢您解决这个问题。最后一个问题是访问我的 index.php 脚本中的数组索引,$pageIntroductionContent。如果我 require cityConfig.php 尝试调用 index 0Warning: file_get_contents(cityConfig.xml) [function.file-get-contents]: failed to open stream,我得到未定义的函数
    • 所以,您在访问cityConfig.xml 时遇到了问题。重新检查文件路径。
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多