SimpleXML and print_r() - why is this empty?

2019-01-04 03:15发布

Hi there here is my xml file: (thefile)

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://nts-de-osm1-pxc/webservices/">
  <Item xmlns:q1="http://systinet.com/wsdl/com/osm/webservices/service/" xsi:type="q1:Document">

    <q1:attributes>
      <q1:Attribute>
        <q1:dataDictionary xsi:nil="true" />
        <q1:dataType>string</q1:dataType>
        <q1:displayName>AEND_DATUM</q1:displayName>
        <q1:key>false</q1:key>
        <q1:name>AEND_DATUM</q1:name>
        <q1:searchable>true</q1:searchable>
        <q1:userAttribute>true</q1:userAttribute>
        <q1:value>10.05.10</q1:value>
      </q1:Attribute>
      <q1:Attribute>
        <q1:dataDictionary xsi:nil="true" />
        <q1:dataType>string</q1:dataType>
        <q1:displayName>AEND_PRUEF_DATUM</q1:displayName>
        <q1:key>false</q1:key>
        <q1:name>AEND_PRUEF_DATUM</q1:name>
        <q1:searchable>true</q1:searchable>
        <q1:userAttribute>true</q1:userAttribute>
        <q1:value>10.05.10</q1:value>
      </q1:Attribute>
    </q1:attributes>
  </Item>
</ArrayOfItem>

Here is my code

$xml = simplexml_load_file($thefile);
print_r($xml);

This is the output

SimpleXMLElement Object
(
    [Item] => SimpleXMLElement Object
        (
        )

)

Why is this Empty?

3条回答
爷、活的狠高调
2楼-- · 2019-01-04 03:47

Don't use print_r() or var_dump() to inspect a SimpleXMLElement, they won't necessarily work on them because SimpleXML uses lots of magic behind the scene. Instead, look at what asXML() returns.

In your case, it doesn't show <q1:attributes/> because they're not in the same namespace.

Edit

To access those namespaced nodes, there are many different ways, most of them discussed here at Stack Overflow. If you can't work it out, please open a new question, since the subject is different. Here's 3 ways to access those elements:

$ArrayOfItem->Item->children("http://systinet.com/wsdl/com/osm/webservices/service/");
$ArrayOfItem->Item->children('q1', true);
$ArrayOfItem->Item->xpath('//q1:Attribute');
查看更多
爷、活的狠高调
3楼-- · 2019-01-04 04:08

The simpleXML parser should provide a meaningful error message that you can fetch and output. Check out the example code in the documentation on libxml_get_errors().

查看更多
SAY GOODBYE
4楼-- · 2019-01-04 04:08

Two things:

  • You are missing the closing tag for q1:attributes.
  • SimpleXML cannot handle <q1:Attributes> type tags. I changed it to <q1> and it works till that tag.

I think you need SimpleXML parser here

查看更多
登录 后发表回答