PHP DomDocument : How remove a div?

2019-07-16 05:28发布

问题:

Here is my code :

$doc = new DOMDocument();
$doc->loadHTML(stripslashes($sContent));

// si le meta existe alors il y a un sondage
if($doc->getElementById('meta') != null){
    $nombreMeta = $doc->getElementById('meta')->nodeValue;
    $numSondage = $doc->getElementById('meta')->getAttribute('class');
    for($i=0;$i<$nombreMeta;$i++){
        $meta = $meta."0,";
    }
    $meta = substr($meta,0,-1); 
    $divMeta = $doc->getElementById('meta');
    $oldchapter = $doc->removeChild($divMeta);
    $oHead = $doc->getElementsByTagName('head')->item(0);
    $oMeta2 = $doc->createElement('meta');
    $oMeta2->setAttribute('name',"metapoll".$numSondage);
    $oMeta2->setAttribute('content',$meta);
    $oHead->insertBefore($oMeta2, $oHead->firstChild);
    $sContent = $doc->saveHTML();
}

I'm trying to remove div with id="meta" ($doc->getElementById('meta')), but I don't know why it doesn't work.

I have tested lots of things like :

$metmet = $doc->documentElement;
$divMeta = $metmet->getElementById('meta')->item(0);
$metmet->removeChild($divMeta);

But it doesn't work. Any ideas ?

回答1:

The removeChild method removes a child element from a node. A div cannot be a child element of the document object, only <html> can be (in an HTML document).

Having found the div you want to remove, you need to fetch its parent node. Then call removeChild on that.

$divMeta->parentNode->removeChild($divMeta)


回答2:

The following code should work:

$divMeta = $doc->getElementById('meta');
$divMeta->parentNode->removeChild($divMeta);
  • removeChild
  • parentNode