Riccardo Malesani
Riccardo Malesani

Reputation: 203

Php parse html dom and count specific rows

I'm using the "Simple php DOM Parser" to parse an html table and count its row.

I solved to count all the rows (tr) in it with this code:

$rows = $table->find('.trClass');
$count = count($rows);
echo $count;

And I correctly get the number of all the rows in the table.

Now I want to count only the rows which contains a specific td (with a specific string).
We could assume that I want to count only the rows with this td:

<td class="tdClass" align="center" nowrap="">TARGET STRING</td>

How can I modify the first code to match this scope?

I tried to use "preg_match" or "preg_match_all" but I don't have much experience in it, so I miss the correct syntax..I think.

Any help is very appreciated!

Upvotes: 1

Views: 3068

Answers (2)

Styxxy
Styxxy

Reputation: 7517

How about:

<?php
$targetString = 'TARGET STRING';
$rows = $table->find('.trClass');

$count = 0;
foreach($rows as $row) {
    foreach($row->find('td') as $td) {
        if ($td->innertext === $targetString) {
            $count++;
            break;
        }
    }
}

Upvotes: 1

Francis Avila
Francis Avila

Reputation: 31621

$target = 'TARGET STRING';

$n_matchingrows = 0;

$rows = $table->find('tr.trClass');
foreach($rows as $row) {
    $cell = $row->find('td.tdClass[align=center][nowrap=""]', 0);
    if ($cell and $cell->innertext===$target) {
       $n_matchingrows += 1;
    }
}

Upvotes: 0

Related Questions