gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:40:39 25 4
gpt4 key购买 nike

我真的很难理解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com