Php 根据属性从xml中删除

Php 根据属性从xml中删除,php,xml,Php,Xml,我的xml文件名为cgal.xml <?xml version="1.0"?> <item> <name><![CDATA[<img src="event_pic/pic1.jpg" />CALENDAR]]></name> <description title="NAM ELIT AGNA, ENDRERIT SIT AMET, TINCIDUNT AC." day="13" month="8" year="

我的xml文件名为cgal.xml

<?xml version="1.0"?>
<item>
  <name><![CDATA[<img src="event_pic/pic1.jpg" />CALENDAR]]></name>
  <description title="NAM ELIT AGNA, ENDRERIT SIT AMET, TINCIDUNT AC." day="13" month="8" year="2010" id="15"><![CDATA[<img src="events/preview/13p1.jpg" /><font size="8" color="#6c6e74">In Gladiator, victorious general Maximus Decimus Meridias has been named keeper of Rome and its empire by dying emperor Marcus Aurelius, so that rule might pass from the Caesars back to the people and Senate. Marcus\' neglected and power-hungry son, Commodus, has other ideas, however. Escaping an ordered execution, Maximus hurries back to his home in Spain, too l</font>]]></description>
</item>
id是动态传递的


我想根据id删除节点

您不需要从SimpleXml加载或导入XML。您可以直接用DOM加载它。此外,您可以使用与问题中相同的方式删除节点。只需将XPath查询更改为

$query = sprintf('//description[@id="%s"]', $id);


如果XML根据实际将id定义为XML id的DTD或模式进行验证,也可以使用XPath代替。这在中进行了解释。

首先,没有
DomDocument::simplexml\u load\u file()
方法。要么使用dom文档,要么不。。。因此,使用DomDocument:

$doc = new DomDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;

$doc->loadXml(file_get_contents('../cgal.xml'));

$element = $doc->getElementById($id);
if ($element) {
    $element->parentNode->removeChild($element);
}
那应该可以帮你

编辑:

正如Gordon指出的,这可能不起作用(我试过了,但并不总是如此)。。。因此,你可以:

$xpath = new DomXpath($doc);
$elements = $xpath->query('//description[@id="'.$id.'"]');
foreach ($elements as $element) { 
    $element->parentNode->removeChild($element);
}
或者,使用SimpleXML,可以在每个节点上递归(性能较低,但更灵活):


你的问题是什么?此外,也许这些问题中有一个能帮上忙:除非他有DTD或模式来验证,否则这将失败。DOM不会识别ID属性本身,但会将其视为常规属性。谢谢@Gordon,我已经用其他两种可能性更新了我的答案。。。
$doc = new DomDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;

$doc->loadXml(file_get_contents('../cgal.xml'));

$element = $doc->getElementById($id);
if ($element) {
    $element->parentNode->removeChild($element);
}
$xpath = new DomXpath($doc);
$elements = $xpath->query('//description[@id="'.$id.'"]');
foreach ($elements as $element) { 
    $element->parentNode->removeChild($element);
}
$simple = simplexml_load_file('../cgal.xml', 'SimpleXmlIterator');
$it = new RecursiveIteratorIterator($simple, RecursiveIteratorIterator::SELF_FIRST);
foreach ($it as $element) {
    if (isset($element['id']) && $element['id'] == $id) {
        $node = dom_import_simplexml($element);
        $node->parentNode->removeChild($node);
    }
}