PHP XML删除父级

时间:2012-04-26 21:12:02

标签: php xml

XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
    <pages>
      <page><title>Home</title><content>Lorem Ipsum</content></page>
      <page><title>Pictures</title><content>Lorem Ipsum</content></page>
      <page><title>Information</title><content>Lorem Ipsum</content></page>
    </pages>
  <css>
    <css-tag><title>background-color</title><value>#FFF</value></css-tag>
  </css>
  <layout>1</layout>
</root>

PHP:

$title = $_GET['0'];

$xml = new DOMDocument('1.0', 'ISO-8859-1');
$xml->formatOutput = true;
$xml->preserveWhiteSpace = true;
$xml->load($location);
$pages = $xml->getElementsByTagName("page");
foreach($pages as $page){
    $pagetitle = $page->getElementsByTagName("title");
    $pagetitlevalue = $pagetitle->item(0)->nodeValue;
    if($title == $pagetitlevalue){
        $pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));
    }
}
$xml->save($location);

此代码仅删除<Title>节点,如何更改它以删除父<Page>节点?

我无法弄清楚如何做到这一点,我只是设法摆脱标题节点并获取大量错误代码

1 个答案:

答案 0 :(得分:2)

虽然我可能会使用xpath,但你可以找到......

$pagetitle->item(0)->parentNode->removeChild($pagetitle->item(0));

并替换为...

$pagetitle->item(0)->parentNode->parentNode->removeChild($pagetitle->item(0)->parentNode);

在XML树中更高一级