0

I have an html table like this

<table>
<tbody>
    <tr>
      <td><table>
          <tbody>
            <tr class="prdLi">
              <td rowspan="2" class="prdNo"><span>310.</span></td>
              <td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
            </tr>
            <tr class="prdLi">
              <td class="prdAc"><span> 1.5L</span></td>
              <td><span>&nbsp;</span></td>
            </tr>
          </tbody>
        </table></td>
    </tr>
  </tbody>
</table>

the table is saved as $html

I want to select the child elements of the class .prdLi

I tried like this:

foreach($html->find('tr.prdLi') as $foo){
   echo $foo;

}

the output that i get is like this

<span>310.</span>
<span>Pepsi</span
.
.
.

but what i actually want to get is the code with the parent element td.like this:

<td rowspan="2" class="prdNo"><span>310.</span></td>
<td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
.
.
.

please help me

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
Ali Dru
  • 1
  • 3

2 Answers2

1

Since Simple HTML DOM Parser supports CSS like selectors, you can use 'tr.prdLi td' to specify all td elements which are children of tr with class prdLi. The following should provide what you are looking for:

$htmlstr = <<<EOD
<table>
<tbody>
    <tr>
      <td><table>
          <tbody>
            <tr class="prdLi">
              <td rowspan="2" class="prdNo"><span>310.</span></td>
              <td colspan="2" class="prdDe" rowspan="2"><span>Pepsi</span></td>
            </tr>
            <tr class="prdLi">
              <td class="prdAc"><span> 1.5L</span></td>
              <td><span>&nbsp;</span></td>
            </tr>
          </tbody>
        </table></td>
    </tr>
  </tbody>
</table>
EOD;

$html = str_get_html($htmlstr);
foreach ($html->find('tr.prdLi td') as $foo) {
    echo $foo . "\n";
}

Note that find() is called on the main simple_html_dom-element. In your example, the result was already limited by a previous find().

andy
  • 2,002
  • 1
  • 12
  • 21
  • but the output is as before, like this: `310. Pepsi310. Pepsi` – Ali Dru Oct 13 '14 at 12:28
  • I tested the above code with version 1.5 ($Rev: 210 $) of the parser and get exactly what you are looking for. Which code exactly are you using? What version or the parser? – andy Oct 13 '14 at 12:31
  • im using the same version as yours `version 1.5 ($Rev: 210 $)` – Ali Dru Oct 13 '14 at 12:38
1

What andy says is correct, but the css for direct child is > *, therefore:

foreach($html->find('tr.prdLi > *') as $foo){
   echo $foo . "\n";
}
pguardiario
  • 53,827
  • 19
  • 119
  • 159