Answer the question
In order to leave comments, you need to log in
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>
<?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");
?>
Answer the question
In order to leave comments, you need to log in
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));
}
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 questionAsk a Question
731 491 924 answers to any question