0
votes

From the documentation:

The XMLReader extension is an XML pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way

I want to go to next but parent node <group> blocks me.

XML Structure

<group name="blabla">
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
</group>
<group name="blabla">
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
 <o>
  <id>Value</id>
  <name>Value</name>
  <category>Value</category>
 </o>
</group> etc..

I want go to next but parent node block me.

<?php
$reader = new XMLReader();
$reader->open($fileTMP);

while (true) {
    if ($reader->nodeType === XMLReader::ELEMENT
        && $reader->name === XML_PRODUCT_ELEMENT_NAME
        && $reader->isEmptyElement === false) {

        $item = simplexml_load_string($reader->readOuterXML(), null, LIBXML_NOCDATA);

        $product = [];
        $product['id'] = trim((string) $item->id);
        $product['name'] = trim((string) $item->name);

        if (isset($item->imgs->i)) {
            foreach ($item->imgs as $image) {
                $product['foto'][] = trim((string) $image->i['url']);
            }
        }

        if (!$reader->next(XML_PRODUCT_ELEMENT_NAME)) {
            break;
        }
    } else if (!$reader->read()) {
        break;
    }
}

$reader->close();
2
Please explain what is meant by "parent node block me". Can you also show what product map contains after execution? - Smartcat

2 Answers

0
votes

I think your main problem is when you get to

     if (!$reader->next(XML_PRODUCT_ELEMENT_NAME)) {
         break;
     }

You would have been reading a sequence of <o> elements and then when the first set finishes, it will get to here, see that it isn't an <o> element and break out of the reading loop. So first comment out/delete this code.

Then to ensure it reads through the document, change

       elseif (!$reader->read()) {

to

       if (!$reader->read()) {

this means this code will always work in the main loop if you don't have an <o> element and skip any unrelated nodes.

0
votes

Simple and better

$reader = new XMLReader();
$reader->open($fileTMP);

while ($reader->read()) {
 if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === XML_PRODUCT_ELEMENT_NAME && $reader->isEmptyElement === false) {
     $item = simplexml_load_string($reader->readOuterXML(), null, LIBXML_NOCDATA);

     $product = [];
     $product['id'] = trim((string) $item->id);
     $product['name'] = trim((string) $item->name);

     if (isset($item->imgs->i)) {
         foreach ($item->imgs as $image) {
             $product['foto'][] = trim((string) $image->i['url']);
         }
     }    
 }
}
$reader->close();