0

The goal is to delete every XML child with the same parent that matches the id.

The problem I've encountered was that only the first XML child was removed. When I ran this file the output was "The id is: 1" and also "CarlCarlok". The script removed the first XML child with the attribute "1". Which also was proven when I checked the XML file afterwards where the comment with id "9" was removed. So..To resolve this issue i have to know:

How do I remove every XML child with the same parent? Because now it only removes the first one it encounters.

<?php
require '../functions.php';

$id = $_GET['id'];
echo "The id is: " . $id . "\n";

$comment_xml_path = '../data/comments.xml';
$comments_xml_file = simplexml_load_file($comment_xml_path);

foreach ($comments_xml_file->comment as $c) {
    echo $c->author;
    if (strcmp($id, $c['parent']) == 0) {
        $dom = dom_import_simplexml($c);
        $dom->parentNode->removeChild($dom);
        echo "ok";
    }
    save_xml($comment_xml_path, $comments_xml_file);

(save_xml() is a function for saving utilizing asXML that we made during class)

The XML file

<?xml version="1.0" encoding="UTF-8"?>
<comments>
    <comment id="6" parent="3" date="20150317224217">
         <author>Carl</author>
         <cmt>3</cmt>
    </comment>
    <comment id="9" parent="1" date="20150312225112">
         <author>Carl</author>
         <cmt>dsa</cmt>
    </comment>
    <comment id="10" parent="1" date="20150356225256">
         <author>Carl</author>
         <cmt>2</cmt>
    </comment>
    <comment id="11" parent="1" date="20150357225257">
         <author>Carl</author>
         <cmt>2</cmt>
    </comment>
</comments>
hakre
  • 193,403
  • 52
  • 435
  • 836
  • The code you've put here in question ends after you save the XML file after you've removed the first match. The rest of the code is not shown. So you perhaps save too early? – hakre Mar 06 '15 at 23:00

2 Answers2

1

Here's a way with SimpleXML and xpath(), which is like SQL for XML:

$id = 1; // parent
$xml = simplexml_load_file("some/path/to/an/xml/file.xml");

$comments = $xml->xpath("/comments/comment[@parent='$id']");

foreach ($comments as $comment) unset($comment[0]);

echo $xml->asXML(); // show result

Comments:

  • line 3: the xpath-statement will select all <comment> where attribute parent = $id. The @ in the statement means attribute. The condition is wrapped in []. The result is stored in $comments as an array of SimpleXML elements.
  • line 4: deleting each <comment> in the array.
michi
  • 6,565
  • 4
  • 33
  • 56
0

If you want to remove all the children, I would instead loop over the childNodes and call removeChild().

Updated Code:

if (strcmp($id, $c['parent'])== 0) {
    foreach ($c->childNodes as $child) {
        $child->parentNode->removeChild($child);
    }
}

This assumes you are using DOMDocument. However, you seem to be mixing this and SimpleXML.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174