我真的很想弄清楚DOMDocument解析.
我正在尝试解决以下问题.
给出以下HTML
Title
Some Content
Some More Content
Other Content
Last Bit of Content
我想在第二段标记之后添加一个带有其他内容的div.
基本上结果需要如下所示
Title
Some Content
Some More Content
Something different
Other Content
Last Bit of Content
在这里看了几篇文章后,我现在感到厌倦了.
解决方法:
您需要使用DOMDocument类来解析字符串到html.解析html后,选择第三个p元素并使用DOMNode::insertBefore在其后插入新元素.
$doc = new DOMDocument();
$doc->loadHTML($html);
// find 3th p tag
$p = $doc->getElementsByTagName("p")->item(2);
// create new div tag
$div = $doc->createElement("div", "Something different");
// insert created element after 3th p
$p->parentNode->insertBefore($div, $p);
$html = $doc->saveHTML();
标签:php,html-parsing,domdocument,html
来源: https://codeday.me/bug/20190608/1198891.html