0

我在 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');

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

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)

另外,我不确定输出中“[]”之间的数字是什么意思。

4

1 回答 1

1

是的,这确实看起来很奇怪。但是,您不能在SimpleXMLElementvar_dump上使用or 。这些元素具有很多魔力,这里是在骗你。我的意思是真的在撒谎,请看:print_rvar_dump

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

正在给予NULL,根本没有SimpleXMLElement

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

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

这确实允许迭代和访问由实体表示的实体。然后var_dump看起来也好多了:

class SimpleXMLElement#4 (1) {
  public $totalInstances =>
  class SimpleXMLElement#3 (1) {
    public $nombre =>
    string(2) "45"
  }
}
于 2013-04-20T13:45:54.180 回答