如何将XML文件转换为SimpleXMLElement()数组?

时间:2010-10-26 14:02:45

标签: php xml arrays simplexml

我有一个XML文件:

<?xml version="1.0" encoding="iso-8859-1"?>
<deadlines>
    <deadline>
        <date>2010-07-01</date>
        <text>Residency Application for Fall Due</text>
    </deadline>
    <deadline>
        <date>2010-06-01</date>
        <text>Residency Application for Summer Due</text>
    </deadline>
    <deadline>
        <date>2010-07-20</date>
        <text>Summer Bill Due</text>
    </deadline>
</deadlines>

当我使用simplexml_load_file()将文件加载到PHP脚本中时,我得到以下内容:

SimpleXMLElement Object
(
    [deadline] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [date] => 2010-07-01
                    [text] => Residency Application for Fall Due
                )

            [1] => SimpleXMLElement Object
                (
                    [date] => 2010-06-01
                    [text] => Residency Application for Summer Due
                )

            [2] => SimpleXMLElement Object
                (
                    [date] => 2010-07-20
                    [text] => Summer Bill Due
                )

        )

)

为了让我的脚本将XML文件作为数组处理,我需要解析该文件并将其转换为以下格式:

Array
(
    [0] => SimpleXMLElement Object
        (
            [date] => 2010-07-01
            [text] => Residency Application for Fall Due
        )

    [1] => SimpleXMLElement Object
        (
            [date] => 2010-06-01
            [text] => Residency Application for Summer Due
        )

    [2] => SimpleXMLElement Object
        (
            [date] => 2010-07-20
            [text] => Summer Bill Due
        )

)

是否有PHP函数来转换XML文件?感谢

2 个答案:

答案 0 :(得分:2)

$deadlines = array();
$sxe = new SimpleXmlElement($xml);
foreach($sxe->deadline as $deadline) {
    $deadlines[] = $deadline;
}
print_r($deadlines);

$sxe = (array) new SimpleXmlElement($xml);
print_r( $sxe['deadline'] );

编辑抱歉,我认为您已熟悉SimpleXml以了解constructor of SimpleXmlElement assumes you are passing the XML as a string。将行更改为

$sxe = new SimpleXmlElement($filename, NULL, TRUE);

或用

替换它
$sxe = simplexml_load_file($filename);

答案 1 :(得分:1)

最简单的方法。

<?php
$data = (array)simplexml_load_file('data.xml');
$data = array_pop($data);
print_r($data);
?>