不理解XML实体和PHP SimpleXMLElement中的输出


Don't understand the output in XML Entities and PHP SimpleXMLElement

我在XML中使用实体,我不理解我的结果。

我有一个调用外部实体的XML文件,这是config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE config [
    <!ENTITY totalInstances SYSTEM "totalInstances.xml">
]>
<config>
    &totalInstances;
</config>

totalInstances.xml文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<totalInstances>
    <nombre>45</nombre>
</totalInstances>
在PHP中,我通过SimpleXMLElement类加载config.xml文件:
$config = simplexml_load_file('config.xml');

然后我输出变量$config与var_dump,这是我不明白的事情:

object(SimpleXMLElement)[3]
  public 'totalInstances' => 
    object(SimpleXMLElement)[5]
      public 'totalInstances' => 
        object(SimpleXMLElement)[6]
          public 'totalInstances' => 
            object(SimpleXMLElement)[8]
              public 'nombre' => string '45' (length=2)

我期望有一个简单的"totalInstances"节点,其中包含节点"nombre"。会发生什么?谢谢你。

编辑:更详细地说,我不明白为什么我得到三个名为"totalInstances"的对象,而在文件totalInstances.xml中只有一个?我期望得到这样的输出:

object(SimpleXMLElement)[3]
      public 'totalInstances' => 
            object(SimpleXMLElement)[8]
                public 'nombre' => string '45' (length=2)

还有,我不太明白输出中"[]"之间的数字是什么意思

是的,这看起来确实很奇怪。但是,您不能在SimpleXMLElement上使用var_dumpprint_r。这些元素是有很多魔力的,这里的 var_dump 是在骗你。我是说真的在撒谎,看:

var_dump($config->totalInstances->totalInstances);

给出NULL,没有SimpleXMLElement

在您的特定情况下,如果您想使用文档作为扩展实体的 SimpleXMLElement ,那么您可以使用LIBXML_NOENT选项(替代实体):

$config = simplexml_load_file('config.xml', NULL, LIBXML_NOENT);

允许遍历和访问由entity/ies表示的实体。var_dump看起来也好多了:

class SimpleXMLElement#4 (1) {
  public $totalInstances =>
  class SimpleXMLElement#3 (1) {
    public $nombre =>
    string(2) "45"
  }
}