Question

hi i want to extract the div part from following html by php preg_match_all, i have multiple tables like shown below , want to extract all div part only from < td > tag that div start like that

$regex ='\<td width=\"178\" height=\"44\" valign=\"top\" background=\"img\/comprar-boton.jpg\" style=\"background-repeat:no-repeat\">(.*?)<\/div>/i'; 
preg_match_all($regex,$pageHtml,$out);
print_r($out);

<table border="0" align="center" cellpadding="1" cellspacing="1">
   <tr>
      <td align="center">
         <a  href="inicio.php?bq=2&amp;id=2005" title="">
            <div style="margin-right:10px;">
               <img src="productos/producto_4779.jpg" width="200" border="0" class="BtnRecorrido" />
            </div>
         </a>
      </td>
   </tr>
   <tr>
      <td align="center" class="MonsterTitulos"><strong>BOXER CALAVERAS</strong></td>
   </tr>
   <tr>
      <td width="178" height="44" valign="top" background="img/comprar-boton.jpg" style="background-repeat:no-repeat">
         <div >
            <a href="inicio.php?bq=2&amp;id=2005">
               <div class="textoHueso12" align="center">$110.00 MXN</div>
            </a>
         </div>
      </td>
   </tr>
</table>
Was it helpful?

Solution

Make use of DOMDocument Class.

<?php
$content=' <table border="0" align="center" cellpadding="1" cellspacing="1">
                    <tr>
                      <td align="center"><a  href="inicio.php?bq=2&amp;id=2005" title="">
                      <div style="margin-right:10px;">
                      <img src="productos/producto_4779.jpg" width="200" border="0" class="BtnRecorrido" />
                      </div>
                      </a></td>
                      </tr>
                    <tr>
                      <td align="center" class="MonsterTitulos"><strong>BOXER CALAVERAS</strong></td>
                      </tr>
                    <tr>
                      <td width="178" height="44" valign="top" background="img/comprar-boton.jpg" style="background-repeat:no-repeat"><div >
                      <a href="inicio.php?bq=2&amp;id=2005">
                        <div class="textoHueso12" align="center">$110.00 MXN</div>
                        </a></div>
                        </td>
                      </tr>
                    </table>';
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach ($dom->getElementsByTagName('td') as $tag) {
    foreach($tag->getElementsByTagName('div') as $divtag)
    {
        foreach($divtag->getElementsByTagName('img') as $imgtag)
        {
         echo $imgtag->getAttribute('src');
        }
    }
}

OUTPUT :

productos/producto_4779.jpg
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top