Seb Gy
Seb Gy

Reputation: 140

Delete node with simplexml

I have this 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>

I do this in 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"); 

In result, just the fist is deleted. I would like to delete all . Why it's not correct?

Thanks.

Upvotes: 1

Views: 6473

Answers (2)

aleation
aleation

Reputation: 4844

This would be the DOM approach, I think it can save you troubles in the future:

$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;

Upvotes: 0

sandy
sandy

Reputation: 1158

Try this.

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

Upvotes: 3

Related Questions