Search code examples
phpsimple-html-dom

How to foreach php array to create new element with simpledom find


Im trying to replace 'richtext' element in html page with a content(summary) i have with [simpledom html]:(https://simplehtmldom.sourceforge.io/manual.htm)

an array variable 'summary' with ["sentences"]=> sentence1 and sentence2 and so on

I tried

  foreach ($summary->sentences as $sentence) {

        $outhtml->find('div[class=richtext]',index)->outertext='<p>'.$sentence.'</p>';
index++;

    }


This save the last element from array into html


  foreach ($summary->sentences as $sentence) {

        $outhtml->find('div[class=richtext]',0)->outertext='<p>'.$sentence.'</p>';

    }

Expected result

<div class='richtext'>
<p>sentence 1</p>
<p>sentence 2</p>
<p>sentence 3</p>
</div>

Solution

  • Rather than use a loop (which can easily overwrite the previous text), you can use implode() to build up the content and then set the inner text from that...

    $html->find('div[class=richtext]',0)->innertext = "<p>".
                 implode("</p><p>", $summary->sentences).
                 "</p>";