我正在嘗試使用 PHP 在我的 $article_content 中插入廣告,我需要根據段落編號放置廣告代碼。
當我對我的 MySQL 進行選擇時,我得到了這個結構:
ID_ARTICLE | 廣告代碼 | 段落
可能大多數文章會有 04 行資料(04 個廣告),例如:
1 | 廣告代碼/廣告代碼 | 0
1 | 廣告代碼/廣告代碼 | 1
1 | 廣告代碼/廣告代碼 | 3
1 | 廣告代碼/廣告代碼 | 5
所以這是我的代碼:
$pdo = ConectarSite();
$sql3 = "
SELECT
art.id,
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
";
$stmt3 = $pdo->prepare($sql3);
$stmt3->execute(['id' => '1']);
$article_content = '<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been</p>';
$doc = new DOMDocument();
$doc->loadHTML($article_content);
while($row3 = $stmt3->fetch()) {
for ($i = 0; $i < $row3['paragraph']; $i ) {
$p = $doc->getElementsByTagName('p');
if ($i == $row3['paragraph']) {
$ads = $doc->createElement('div', $row3['adcode']);
$p->insertBefore($ads);
}
}
}
echo $doc->saveHTML();
我不知道如何正確創建 for
uj5u.com熱心網友回復:
這是我所說的意思的一個例子:
您應該
DOMDocument在主 while ()` 回圈之外創建、填充和輸出,只有廣告的插入應該在回圈內。
$doc = new DOMDocument();
$doc->loadHTML($article_content);
foreach ($adverts as $row3) {
$paragraphs = $doc->getElementsByTagName('p');
for ($i = $paragraphs->length; --$i >= 0; ) {
$paragraph = $paragraphs->item($i);
if ($i 1 == $row3['paragraph']) {
$ads = $doc->createElement('div', $row3['adcode']);
$paragraph->parentNode->insertBefore($ads, $paragraph);
}
}
}
echo $doc->saveHTML();
請注意,段落專案從 0 到 n-1,并且由于您的段落編號從 1 到 n,因此需要進行更正。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/463656.html
