phphtmlsimpledom

insert div between content using foreach with simple html dom parser


I'm using PHP simple dom parser, says my markup is like this

<table class="tb">..</table>
<table>..</table>
<table>..</table>

I tried

$banner = '<div class="ads">blablabla</div>';
foreach($html->find('tb') as $table){
    $table->outertext .= $banner;
}

but it loops all the table. I tried find('div[class="tb"][1]') but it doesn't work. I want a div appear only once btw the first and second table.


Solution

  • First of all, you are trying to find div with class tb whereas you should be looking for the table element. Next, to 'append' the existing text with the $banner value, you need to use .= operator so that your table code is not erased. And then finally, you save the changes. The code should look like:

    foreach($html->find('table[class=tb]') as $element){
           echo $element->src . '<br>';
           $element->outertext .= $banner;
    }
    
    $html->save();
    

    The output would be:

    <table class="tb">..</table><div class="ads">banner</div>  <table>..</table>  <table>..</table>