【问题标题】:SimpleXML showing unexpected behaviour显示意外行为的 SimpleXML
【发布时间】:2017-04-27 23:34:50
【问题描述】:

我有一个名为 conf.xml 的 XML 文件,我正在尝试通过一个简单的 php 脚本(位于同一目录中)显示此 XML 文件的内容,如下所示:

conf.xml

<?xml version="1.0" encoding="UTF-8"?>
<registration_info>
  <organization name="Home" />
</registration_info>

PHP 脚本:

$data=simplexml_load_file("conf.xml");
$node=$data->registration_info;
$subnode=$node->organization;
echo (string) $subnode['name']; // Displays null string

我觉得代码没有问题,但输出出乎意料,因为预期的输出是“Home”。谁能帮我解决这个问题并解释一下解决方案吗?

提前致谢。

【问题讨论】:

  • 您必须忽略顶级节点(本例中为registration_info)。
  • @ÁlvaroGonzález 是吗?想解释一下原因吗?
  • 我想这是一个设计决定(毕竟它是多余的,因为总是需要一个而且只能有一个)但我只能推测。

标签: php xml simplexml


【解决方案1】:

这里给出的现有答案是正确的,但解释相当混乱。 SimpleXML 没有隐藏您的 XML 的根节点,只是您拥有的对象已经是那个节点。

每个SimpleXMLElement 对象代表XML 文档树中的一个特定节点。 SimpleXML 中没有单独的对象表示“整个文档”,因此当您运行simplexml_load_file 时,返回的对象是根节点的SimpleXMLElement

$root_node = simplexml_load_file("conf.xml");
echo $root_node->getName(); // registration_info

$child_node = $root_node->organization;
// Short for $root_node->organization[0];
// meaning "get the first child with name 'organization'
echo $child_node->getName(); // organization

【讨论】:

    【解决方案2】:

    试试这个希望这会对你有所帮助。您只需删除 $node=$data-&gt;registration_info;

    Try this snippet here

    <?php
    
    ini_set('display_errors', 1);
    $data=simplexml_load_file("conf.xml");
    $subnode=$data->organization;
    echo (string) $subnode['name'];
    

    输出: print_r($data)

    SimpleXMLElement Object
    (
        [organization] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [name] => Home
                    )
    
            )
    
    )
    

    【讨论】:

    • 您能解释一下您的解决方案吗?
    • 为什么忽略了registration_info节点?
    • @hecate 如果您只是查看我已更新的帖子,则没有密钥registration_info
    • @hecate 你试图访问一个实际上并不存在的密钥。
    • @hecate registration_info 是您的 xml 的 root 节点。从 $data 创建 xml 对象会隐式隐藏您的 root 节点,您可以在不访问根节点的情况下开始使用对象,而直接访问所有 chlid 节点。
    猜你喜欢
    • 2021-07-30
    • 2017-08-16
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2013-01-19
    • 1970-01-01
    相关资源
    最近更新 更多