php对xml文件中节点的删除\编辑
使用getElementsByTagName()方法删除\编辑XML节点
三个文件:
1.root.xml
2.remove.php —— 删除节点
3.replace.php —— 替换节点
root.xml
child1 content
child2 content
child3 content
child1 content
child2 content
child3 content
remove.php
$xml_str = file_get_contents("root.xml"); //将root.xml文件中的内容读入一个字符串
$doc = DOMDocument::loadXML($xml_str); //载入这个字符串
//取得元素$child2
$root = $doc->documentElement;
$child2 = $root->getElementsByTagName("child2")->item(0);
//删除$child2对象
$root->removeChild($child2);
//保存文件
$doc->formatOutput = true;
$doc->saveXML();
$doc->save("root.xml");
?>
$xml_str = file_get_contents("root.xml"); //将root.xml文件中的内容读入一个字符串
$doc = DOMDocument::loadXML($xml_str); //载入这个字符串
//取得元素$child2
$root = $doc->documentElement;
$child2 = $root->getElementsByTagName("child2")->item(0);
//删除$child2对象
$root->removeChild($child2);
//保存文件
$doc->formatOutput = true;
$doc->saveXML();
$doc->save("root.xml");
?>
replace.php
$xml_str = file_get_contents("root.xml"); //将root.xml文件中的内容读入一个字符串
$doc = DOMDocument::loadXML($xml_str); //载入这个字符串
//取得元素$child3
$root = $doc->documentElement;
$child3 = $root->getElementsByTagName("child3")->item(0);
//创建一个newchild元素来替代child3
$root->replaceChild(new DOMElement("newchild", "new content"), $child3);
//保存文件
$doc->formatOutput = true;
$doc->saveXML();
$doc->save("root.xml");
?>
$xml_str = file_get_contents("root.xml"); //将root.xml文件中的内容读�