PHP - 在php中删除具有特定属性的子项

时间:2015-03-04 22:26:17

标签: php xml parent-child elements

  

目标是删除具有与id匹配的父级的每个XML子级。

我遇到的问题是只删除了第一个XML子项。当我运行这个文件时,输出是“id是:1”,还有“CarlCarlok”。该脚本删除了具有属性“1”的第一个XML子项。当我在之后检查了具有id为“9”的注释的XML文件时,也证明了这一点。所以..要解决这个问题,我必须知道:

  

如何删除具有相同父级的每个XML子级?   因为现在它只删除它遇到的第一个。

<?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()是一个用于保存我们在课堂上使用asXML的函数)

XML文件

<?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>

2 个答案:

答案 0 :(得分:1)

这是SimpleXMLxpath()的一种方式,类似于SQL的{​​{1}}:

XML

评论:

  • 第3行:$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 - 语句将选择属性xpath = <comment>的所有parent。语句中的$id表示属性。条件包含在@中。结果存储在[] $commentsarray元素中。
  • 第4行:删除SimpleXML中的每个<comment>

答案 1 :(得分:0)

如果你想删除所有孩子,我会转而childNodes并呼叫removeChild()

更新代码:

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

这假设您使用的是DOMDocument。但是,您似乎正在混合使用此SimpleXML