php - 如何使用 php 在 html 中的特定元素之后插入新元素?

标签 php html html-parsing domdocument

我真的很难理解 DOMDocument 解析。 我正在尝试解决以下问题。 给定以下 HTML

<h1>Title</h1>
<p>Some Content</p>
<p>Some More Content</p>
<p>Other Content</p>
<p>Last Bit of Content</p>

我想在第二个段落标记之后添加一个带有其他内容的 div。 本质上,结果需要如下所示

<h1>Title</h1>
<p>Some Content</p>
<p>Some More Content</p>
<div>Something different</div> <!-- new tag -->
<p>Other Content</p>
<p>Last Bit of Content</p>

看了这里的一些帖子后,我现在已经厌倦了挠头。

最佳答案

您需要使用 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 - 如何使用 php 在 html 中的特定元素之后插入新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39984379/

相关文章:

php - ini_set 'session.gc_maxlifetime' 为 1 天

html - 图片在 Windows 上无法正确调整大小,怎么办?

perl - 在使用 WWW::Mechanize 获取 <td> 标记内的 <a> 时获取 <td> 文本

html - CSS3 折叠展开效果

jquery - Bootstrap 工具提示不适用于动态生成的行

python - Scrapy:使用编码和 POST 作为 JSON 数组从多个元素中提取

python - 用于 HTML 解析的最佳 Python 模块

php - 商业智能时间机器 (PHP/MySQL)

PHP MySQL插入忽略插入太多数据

php - 添加、删除和更新网页中评论的标签