A
A
AleDv2014-12-27 14:23:50
PHP
AleDv, 2014-12-27 14:23:50

Why are elements in the XML document not being removed?

Hello. I have a file with the following structure

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://mysite.local/?title='Заголвоок 3'</loc>
    <lastmode>2014-12-27</lastmode>
    <priopity>0.6</priopity>
  </url>
  <url>
    <loc>http://mysite.local/?title='Заголвоок 3'</loc>
    <lastmode>2014-12-27</lastmode>
    <priopity>0.6</priopity>
  </url>
  <url>
    <loc>http://mysite.local/?title='Заголвоок 3'</loc>
    <lastmode>2014-12-27</lastmode>
    <priopity>0.6</priopity>
  </url>
  <url>
    <loc>http://mysite.local/?title='Заголвоок 3'</loc>
    <lastmode>2014-12-27</lastmode>
    <priopity>0.6</priopity>
  </url>
  <url>
    <loc>http://mysite.local/?title='Заголовок 0'</loc>
    <lastmode>2014-12-27</lastmode>
    <priopity>0.6</priopity>
  </url>
</urlset>

Task: remove all elements.
I decide:
<?php

  $dom = new DOMDocument('1.0', 'utf-8');
  $dom->formatOutput = true;
  $dom->preserveWhiteSpace = false;
  $dom->load("sitemap.xml");
  
  $sitemap = $dom->documentElement;
    
  $items = $sitemap->getElementsByTagName('url');
  foreach($items as $item)
  {
    $sitemap->removeChild($item);
  }
  $dom->save("sitemap1.xml");
?>

As a result, only 2 out of 5 elements are removed. Tell me where I made a mistake and what needs to be done to remove all elements?
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2014-12-27
@AleDv

The foreach iterator pointer is placed on the element with index 0, then this element is removed, and the numbering shifts accordingly. The iterator jumps to the element at index 1, skipping the element at index 0.
You could do this:

while($items->length) {
    $sitemap->removeChild($items->item(0));
}

O
OlegLazarenko, 2014-12-27
@OlegLazarenko

Use this loop

for($i = 0, $item = $items->item($i); $item; $item = $items->item($i)) {
    $sitemap->removeChild($item);
}
When you remove an element, you change the object, and foreach does not know about it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question