无法使用PHP读取xml文件

时间:2013-09-19 19:49:31

标签: php xml web

我正在使用

加载xml文件
$xml = simplexml_load_file('status.cfg');

XML文件遵循以下方案

    <statuses>
    <status>
        <title>Blackboard</title>
        <shorttitle>blackboard</shorttitle>
        <level>1</level>
        <greenstatus>checked</greenstatus>
        <yellowstatus></yellowstatus>
        <redstatus></redstatus>
    </status>

    <status>
        <title>Faculty/Staff Email</title>
        <shorttitle>fsemail</shorttitle>        
        <level>2</level>
        <greenstatus></greenstatus>
        <yellowstatus>checked</yellowstatus>
        <redstatus></redstatus>
    </status>
</statuses>

它读得很好。但是当我使用

创建一个新的xml文件时
$doc = new SimpleXMLElement('<xml/>');

写下来
$doc->asXml('status.cfg');

它将xml文件像这样重新启动

<?xml version="1.0"?>
<xml>
        <statuses>
        <status>
            <title>Blackboard</title>
            <shorttitle>blackboard</shorttitle>
            <level>1</level>
            <greenstatus>checked</greenstatus>
            <yellowstatus></yellowstatus>
            <redstatus></redstatus>
        </status>

        <status>
            <title>Faculty/Staff Email</title>
            <shorttitle>fsemail</shorttitle>        
            <level>2</level>
            <greenstatus></greenstatus>
            <yellowstatus>checked</yellowstatus>
            <redstatus></redstatus>
        </status>
    </statuses>
</xml>

这导致我的原始页面无法使用

等命令读取它
$xml->status[0]->shorttitle;

但是,删除外部xml标记时可以读取它。有任何想法吗?

1 个答案:

答案 0 :(得分:3)

在一种情况下,<statuses>是根节点,而在另一种情况下,<xml>是根节点,<statuses>是第一个嵌套节点。我不明白为什么你会期望添加另一个嵌套级别并能够以相同的方式读取数据。在您的情况下,当<xml>是根节点时,您需要读取数据,如

$xml->statuses->status[0]->shorttitle