Skip to content

Removal during NodeList iteration breaks loop #13863

Closed
@nielsdos

Description

@nielsdos

Description

The following code:

<?php

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML(
    <<<EOXML
    <x>
        <item1 />
        <item2 />
        <item3 />
        <item4 />
        <item5 />
    </x>
EOXML
);

foreach ($doc->documentElement->childNodes as $i => $node) {
    echo $node->localName . PHP_EOL;
    if ($i === 2) {
        $node->remove();
    }
}

https://3v4l.org/TJLvF

Resulted in this output:

item1
item2
item3

But I expected this output instead:

item1
item2
item3
item5

Source: nielsdos#93 (comment)
Credits to @veewee. Similar issue exists for attributes.

PHP Version

Since always

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions