Search code examples
phphtmlhtml-tablesimple-html-dom

Is there anyway that I can get the table row with a specific td value with PHP or Simple HTML DOM?


Say I have the following table:

<table>
    <thead>
        <tr>
            <th>Country<th>
            <th>Currency Name</th>
            <th>Currency Code</th>
    <tbody>
        <tr>
            <td>Austria</td>
            <td>Euro</td>
            <td>EUR</td>
        </tr>
        <tr>
            <td>South Africa</td>
            <td>South African Rand</td>
            <td>ZAR</td>
        </tr>
        <tr>
            <td>Greece</td>
            <td>Euro</td>
            <td>EUR</td>
        </tr>
    </tbody>
</table>

How can I get the whole <tr> and contents containing <td>ZAR</td>? With Simple HTML DOM and PHP?


Solution

  • $string = '...'; // your HTML string
    
    $html = str_get_html($string);
    
    foreach ($html->find('tr') as $tr) {
        $flag = 0;
        foreach ($tr->find('td') as $td) {
            if ($tr->plaintext === 'ZAR') {
                $flag = 1;
                break;
            }
        }
        if ($flag === 1) {
            echo $tr."\n";
        }
    }