doulezhi5326 2017-01-03 21:49
浏览 33
已采纳

DOMDocument使用PHP通过标识符删除div及其内容

Hi I wanna remove a line from a HTML file with PHP like this:

<div id="buttons">
    <div id="buttonid_4"><a href="#">Button 4</a></div>
    <div id="buttonid_3"><a href="#">Button 3</a></div>
    <div id="buttonid_2"><a href="#">Button 2</a></div>
    <div id="buttonid_1"><a href="#">Button 1</a></div>
</div>

So, I wanna remove the buttonid_4, and it content. That it will be like this:

<div id="buttons">
    <div id="buttonid_3"><a href="#">Button 3</a></div>
    <div id="buttonid_2"><a href="#">Button 2</a></div>
    <div id="buttonid_1"><a href="#">Button 1</a></div>
</div>

First I think it is easy, but I can't found the answer :|

I tried: "as simple"

                    $dom = new DOMDocument('1.0', 'utf-8');
                    $dom->loadHTMLFile($The_Path_For_File);
                    $element = $dom->getElementById('buttonid_'. $Button_Id);
                    $element->parentNode->removeChild($element);
                    $dom->saveHTMLFile($The_Path_For_File);

I got

Call to a member function removeChild() on a non-object

and everytime when I tried with GetElementById, so I continue with XPATH:

                    $xpath = new DOMXpath($dom);

                    $nodeList = $xpath->query('//div[@id="buttonid'.$Button_Id.'"]');
                    foreach($nodeList as $element){
                        $dom->$element->removeChild($element);
                    }
                    $dom->saveHTMLFile($The_Path_For_File);

I didn't get error, the notepad requested the refresh for file, but no change Anyone know how to produce this?

  • 写回答

1条回答 默认 最新

  • doushi2902 2017-01-03 23:29
    关注

    The use of getElementById requires a Document Type Declaration (DTD). PHP Documentation

    Notice your HTML fails validation $dom->validate()

    Just add <!DOCTYPE html> to your HTML and it will work.

    For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?