D
D
Dmitry Spiridonov2018-07-19 13:46:22
PHP
Dmitry Spiridonov, 2018-07-19 13:46:22

How to parse xml (in php)?

I am working with a certain API
. The API responds to my request in xml format.
Usually the response comes like this:

<?xml version="1.0" ?>
<root numrecords="3">
  <node1 index="0" result="0" saleid="98556" ticketbarcode="39040056074800160611" />
  <node2 index="1" result="0" saleid="98557" ticketbarcode="22040058074800160611" />
  <node3 index="2" result="0" saleid="98558" ticketbarcode="10040060074800160611" />
</root>

There are no problems here, I do something like this:
// $result - сюда приходит ответ в виде xml
  $dom = new DomDocument();
  $dom->loadXML($result);
  $root = $dom->documentElement;
  $nodes = $root->childNodes;
  foreach($nodes as $node) {
     echo $node->getAttribute("ticketbarcode");
  }

But sometimes (actually often) something goes wrong and I get xml in a different format:
<?xml version="1.0" ?>
<root numrecords="3">
  <node1 index="0" result="0" saleid="98556" ticketbarcode="39040056074800160611">
    <node2 index="1" result="0" saleid="98557" ticketbarcode="22040058074800160611">
      <node3 index="2" result="0" saleid="98558" ticketbarcode="10040060074800160611">
      </node3>
    </node2>
  </node1>
</root>

and everything breaks...
It's useless to argue with API developers....
Maybe someone knows how to get all child elements regardless of their nesting level?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bears, 2018-07-19
@spirik

Try this instead:
here it is:
$nodes = $root->getElementsByTagName('*');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question