使用PHP删除XML中的节点内的节点

时间:2012-12-08 14:02:30

标签: php xml removechild

我想从我的XML文件中删除一个特定的节点,似乎我在代码中遗漏了一些东西! 你可以帮我搞清楚吗,例如我想删除标签及其所有内部标签。

XML结构:

    <students>
    <student>
     <username>sally</username>
     <subjects>
    <subjects>sub1</subjects>
    <subjects>sub2</subjects>
    <subjects>sub3</subjects>
     </subjects>
    </student>
<student>
     <username>jojo</username>
     <subjects>
    <subjects>sub1</subjects>
    <subjects>sub2</subjects>
    <subjects>sub3</subjects>
 <subjects>sub4</subjects>
 <subjects>sub5</subjects>
     </subjects>
    </student>
    </students>

功能:

 public static function delete_subjects($UserName, $fileName) {
        //delete from xml
        $xml = new DOMDocument();
        $xml->load($fileName);

        $users = $xml->getElementsByTagName('student');
        foreach ($users as $user) {
          $username = $user->getElementsByTagName('username')->item(0)->nodeValue;
          if ($username == $UserName) {
                $p=$user->getElementsByTagName('subjects')->item(0);
                $xml->documentElement->removeNode($p);

                break;
            }
        }
        $xml->save($fileName);
    }

致电:

delete_subjects('jojo', $fileName);

1 个答案:

答案 0 :(得分:0)

而不是$xml->documentElement->removeNode($p);尝试使用$user->removeChild($p);

修改:甚至$p->parentNode->removeChild($p);