Reputation: 480
I am trying to insert ads to my $article_content using PHP, I need to place the ad code according the paragraph number.
When I do a select to my MySQL I got this structure:
ID_ARTICLE | AD CODE | PARAGRAPH
Probably the most of articles gonna have 04 rows of data (04 ads), something like:
1 | adcode/adcode | 0
1 | adcode/adcode | 1
1 | adcode/adcode | 3
1 | adcode/adcode | 5
So this is my code:
$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();
I don't know how to create the for correctly
Upvotes: 1
Views: 201
Reputation: 16741
Here's an example of what I meant when I said:
You should create, fill and output your
DOMDocument
outside the main while ()` loop, only the inserting of the ads should be inside the loop.
$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();
Notice that the paragaphs items run from 0 to n-1, and since your paragraph numbering runs from 1 to n, a correction is needed.
Upvotes: 1