dongzhan8620 2012-01-10 16:09
浏览 17
已采纳

使用php Dom删除id的段落

I'm trying to find paragraphs with the id "test" and remove them from a html string, I've tried using php Dom Document but the html I'm searching is badly formed and I get errors

$caption = "blah blah<p id ='test'>Test message</p>";
$doc = new DOMDocument();
$doc->loadHTMLFile($caption);
$xmessage = $doc->getElementById('test');

returns Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Unexpected end tag : br i

Is there a way to suppress the warnings? Thanks

  • 写回答

4条回答 默认 最新

  • duanbozhong9689 2012-01-10 16:30
    关注

    You can use following code to remove a para with id='test':

    $caption = "blah blah<p id='test'>Test message</p><p id='foo'>Foo Bar</p>";
    $doc = new DOMDocument();
    $doc->loadHTML($caption);
    $xpath = new DOMXPath($doc);
    $nlist = $xpath->query("//p[@id='test']");
    $node = $nlist->item(0);
    echo "Para: [" . $node->nodeValue . "]
    ";
    $node->parentNode->removeChild($node);
    echo "Remaining: [" . $doc->saveHTML() . "]
    ";
    

    OUTPUT:

    Para: [Test message]
    Remaining: [<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><body>
    <p>blah blah</p>
    <p id="foo">Foo Bar</p>
    </body></html>
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探