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

。_饼干妹妹 提交于 2019-11-28 12:35:14

问题


I use entities in XML and I don't understand my results.

I have an XML file wich calls an external entity, this is config.xml :

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

Here is the file totalInstances.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<totalInstances>
    <nombre>45</nombre>
</totalInstances>

So in PHP I load the file config.xml with the help of the Class SimpleXMLElement :

$config = simplexml_load_file('config.xml');

Then I output the variable $config with a var_dump, and here is the thing I don't understand :

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

I expected to have a simple "totalInstances" node which contains the node "nombre" . What happens ? Thanks you.

edit : For more details, I don't understand why I get three objects named "totalInstances" while there are only one in the file totalInstances.xml ? I expected to have this output :

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

Also, I'm not sure to understand what means the number between the "[]" in the output.


回答1:


Yes, this does really look weird. However, you can not use var_dump or print_r on a SimpleXMLElement. These elements are with a lot of magic and the var_dump here is lying to you. I mean really lying, see:

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

Is giving NULL and no SimpleXMLElement at all.

In your specific case if you want to make use of the document as a SimpleXMLElement with expanded entities, then you can use the LIBXML_NOENT option (substitute entities):

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

This does allow to iterate over and access the entities that are represented by the entity/ies. The var_dump then looks much better, too:

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


来源:https://stackoverflow.com/questions/16119597/dont-understand-the-output-in-xml-entities-and-php-simplexmlelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!