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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程