PHP DomDocument : How remove a div?

别说谁变了你拦得住时间么 提交于 2020-01-04 15:13:31

问题


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


来源:https://stackoverflow.com/questions/12955079/php-domdocument-how-remove-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!