
本文介绍如何使用 PHP 和 DOMDocument 将 MySQL 中配置的广告代码精准插入到 HTML 文章的指定 段落位置(如第1、第3、第5段后),避免 DOM 操作错误与索引错位问题。
本文介绍如何使用 php 和 domdocument 将 mysql 中配置的广告代码精准插入到 html 文章的指定 `
` 段落位置(如第1、第3、第5段后),避免 dom 操作错误与索引错位问题。
在动态内容渲染场景中,常需将广告代码按预设段落序号(如“第2段之后”“第5段之前”)注入文章 HTML。但直接遍历
标签并使用 insertBefore() 时,若逻辑嵌套不当(如在 while 循环内重复创建 DOM 或误用索引),极易导致广告错位、重复插入或 DOM 异常。核心要点在于:DOM 初始化与最终输出应置于循环外部,仅广告插入逻辑在循环内执行;同时注意数据库中 paragraph 字段为 1-based(即 1 表示首段),而 DOM 节点索引为 0-based,需做 +1 对齐校正。
以下为完整、健壮的实现方案:
// 1. 数据库查询(推荐先获取全部广告配置,避免在循环中多次查询)
$pdo = ConectarSite();
$sql = "
SELECT ab.adcode, ap.paragraph
FROM artigos art
LEFT JOIN anuncios_artigo aa ON art.id = aa.id_artigo
LEFT JOIN anuncios_bloco ab ON aa.id_anuncios_bloco = ab.id
LEFT JOIN anuncios_posicao ap ON aa.id_anuncios_posicao = ap.id
WHERE art.id = :id
";
$stmt = $pdo->prepare($sql);
$stmt->execute(['id' => 1]);
$adverts = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 2. 加载原始文章内容(确保是完整 HTML 片段,含 <html><body> 结构更稳妥)
$article_content = '<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
<p>Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill12116" title="DeepBI DHTML 页面生成器"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d3191a227.jpg" alt="DeepBI DHTML 页面生成器" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill12116" title="DeepBI DHTML 页面生成器">DeepBI DHTML 页面生成器</a>
<p>生成可在 deepbi 沙箱 iframe 内运行或作为独立文件运行的交互式 HTML 页面,使用 `window.deepbi` JS SDK 实现数据查询、空间管理、文件浏览及用户操作。当用户提出以下需求时启用该能力:
- 创建 KPI 仪表盘、数据表格、文件浏览器、成员列表、管理页面;
- 明确要求“转成 dhtml”、“转译成 HTML”、“把 XX 页面转成……”、“控制台页面”、“管理后台”、“DeepBI 页面迁移”;
- 提及位于 `apps/console/src/featur</p>
</div>
<a href="/xiazai/skill12116" title="DeepBI DHTML 页面生成器" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<p>It was popularised in the 1960s with the release of Letraset sheets.</p>
<p>More recently with desktop publishing software like Aldus PageMaker.</p>';
// 3. 初始化 DOMDocument(关键:只初始化一次!)
$doc = new DOMDocument();
libxml_use_internal_errors(true); // 忽略 HTML 解析警告(如缺少 <html>)
$doc->loadHTML('<?xml encoding="utf-8">' . $article_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
// 4. 遍历每条广告配置,精准插入到对应段落前
foreach ($adverts as $row) {
$paragraphs = $doc->getElementsByTagName('p');
$targetIndex = (int)$row['paragraph'] - 1; // 转换为 0-based 索引
// 边界检查:防止越界(如 paragraph=10 但只有 4 段)
if ($targetIndex >= 0 && $targetIndex < $paragraphs->length) {
$targetP = $paragraphs->item($targetIndex);
$adsDiv = $doc->createElement('div', $row['adcode']);
$adsDiv->setAttribute('class', 'ad-inserted'); // 可选:添加样式标识便于调试
// 插入到目标 <p> 元素之前(即显示在该段上方)
$targetP->parentNode->insertBefore($adsDiv, $targetP);
}
}
// 5. 输出清洗后的 HTML(去除多余声明,仅保留 body 内容)
$cleanHtml = '';
$body = $doc->getElementsByTagName('body')->item(0);
if ($body) {
foreach ($body->childNodes as $child) {
$cleanHtml .= $doc->saveHTML($child);
}
}
echo $cleanHtml;✅ 关键注意事项:
-
索引对齐:数据库字段 paragraph = 1 对应首个
(索引 0),务必执行 $targetIndex = $row['paragraph'] - 1;
- DOM 安全加载:使用 LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD 防止 DOM 自动补全 /,再手动提取 body 内容,确保输出纯净;
- 边界防护:插入前校验 $targetIndex 是否在有效范围内,避免 item() 返回 null 导致致命错误;
- 性能优化:一次性查出所有广告数据(fetchAll),而非在循环中反复查询;
-
调试建议:为插入的 添加 class="ad-inserted" 或 data-ad-pos="3" 属性,便于前端验证位置。
通过此方案,您可稳定、可维护地实现“按段落编号精准插广告”的业务需求,适用于 CMS、资讯站、自媒体平台等多场景。


















