Hi i have a code like this:
$doc = new DOMDocument();
$doc->Load('courses.xml');
foreach ($doc->getElementsByTagName('courses') as $tagcourses)
{
foreach ( $tagcourses ->getElementsByTagName('course') as $tagcourse)
{
if(($tagcourse->getAttribute('instructorId')) == $iid){
$tagcourses->removeChild($tagcourse);
}
}
}
$doc->Save('courses.xml');
And i have a xml file:
<courses>
<course courseId="1" instructorId="1">
<course_code>456</course_code>
<course_name>bil</course_name>
</course>
<course courseId="2" instructorId="2">
<course_code>234</course_code>
<course_name>math</course_name>
</course>
<course courseId="3" instructorId="2">
<course_code>341</course_code>
<course_name>cs</course_name>
</course>
<course courseId="4" instructorId="2">
<course_code>244</course_code>
<course_name>phyc</course_name>
</course>
</courses>
In this code i tried to remove elements which has instructor id that specified with iid.The problem is all courses that has this instructor id must be removed.But in my program just the first course that has this iid is being removed.Can you suggest a solution?Thanks.
The
getElementsByTagName()is returning a live nodelist. If you remove an element from it in a loop, the loop is then iterating over a different set of elements than it started with, and the results are unpredictable. Instead, store the nodes you want to remove on an array, then iterate over that and remove them.