使用simplexml删除节点

时间:2013-04-22 13:21:34

标签: php simplexml nodes

我有这个xhtml:

<?xml version="1.0" encoding="UTF-8"?>
<html>
    <head>
        <meta charset="utf-8"></meta>
    </head>
    <body>
        <nav>
            <ol>
                <li>
                    <a href="cover.xhtml">Cover</a>
                </li>
                <li>
                    <a href="page002.xhtml">P002</a>
                </li>
                <li>
                    <a href="page005.xhtml">P005</a>
                </li>
                <li>
                    <a href="page038.xhtml">P038</a>
                </li>
            </ol>
        </nav>
    </body>
</html>

我在php中这样做:

  copy("nav.xhtml", "nav.xml");
  $doc1 = simplexml_load_file("nav.xml");
  foreach($doc1->body->nav->ol->li->a as $seg){ 
       $dom=dom_import_simplexml($seg);
       $dom->parentNode->removeChild($dom);
  }
  $doc1->asXml("nav.xhtml"); 

结果,只有拳头被删除。我想删除所有。为什么不正确?

感谢。

2 个答案:

答案 0 :(得分:3)

试试这个。

foreach($xml->body->nav->ol->li as $items)
{
    unset($items->a);
}

答案 1 :(得分:0)

这将是DOM方法,我认为它可以为您节省麻烦:

$dom = new DOMDocument();
$dom->load($file);

$ol = $dom->getElementsByTagName('ol')->item(0);
$list_elements = $ol->getElementsByTagName('li');

foreach($list_elements as $li){
    $links = $li->getElementsByTagName('a');
    foreach($links as $a){
        $li->removeChild($a);
    }
}

$output = $dom->saveXML();

echo $output;