I
I
Ivan Komarov2020-04-29 07:23:49
PHP
Ivan Komarov, 2020-04-29 07:23:49

How does XMLReader work in PHP?

Please explain the features of the Read method.
Let's say there is a code

$xmlUrl = file_get_contents('feed.xml');
  $xmlReader = new XMLReader();
  $xmlReader->xml($xmlUrl);
  while ($xmlReader->read()) {
    if ($xmlReader->name === 'offer') {
      var_dump ($xmlReader->getAttribute('internal-id'));
      $xmlReader->next();
    }
  }
  $xmlReader->close();


Feed example
<offer internal-id="1">
</offer>
<offer internal-id="2">
</offer>
<offer internal-id="3">
</offer>


This code produces the expected result, i.e.
1
2
3

However, if $xmlReader->next() is removed, then the loop will process each offer node twice and I see a duplicate id in the output, i.e.
1
1
2
2
3
3

Could you explain why this behavior occurs?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question