在SO上尝试了很多例子但没有一个有效。
目标:按特定 id =
删除节点(单元)及其子节点filename.xml中
<archive>
<unit id="0424670018">
<data>Blah blah blah #1</data>
<gdate>2018-05-28 00:42:46</gdate>
</unit>
<unit id="0450170018">
<data>Blah blah blah #2</data>
<gdate>2018-05-28 00:45:01</gdate>
</unit>
</archive>
使用的代码,不确定为什么它在加载时不起作用:
$id = '0450170018';
$file = 'filename.xml';
$xml = simplexml_load_string($file);
foreach($xml->archive as $fileload){
if($fileload->unit['@id'] == $id){
$dom = dom_import_simplexml($fileload);
$dom->parentNode->removeChild($dom);
}
}
答案 0 :(得分:0)
您需要使用“DOMDocument”类
$doc = new DOMDocument;
$doc->load('filename.xml');
$xml = $doc->documentElement;
$id = '0450170018';
$domNodeList = $xml->getElementsByTagname('unit');
foreach ( $domNodeList as $domElement ) {
$valueID = $domElement->getAttribute('id');
if($valueID == $id)
{
$xml->removeChild($domElement);
}
}
$doc->save('filename.xml');
答案 1 :(得分:0)
您可以使用Xpath获取节点。它允许直接获取匹配节点。
$id = '0450170018';
$document = new DOMDocument();
$document->load('filename.xml');
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate("//unit[@id='$id']") as $unitNode) {
$unitNode->parentNode->removeChild($unitNode);
}
$document->save('filename.xml');