Search code examples
phpphpquery

phpQuery - Get data from table with no class or id


I'm trying to get some data from a table, where the tag has no id, class or any other attribute that can identify it.

The table structure is something like this:

<table>
<tr>
    <td><b>Type</b></td>
    <td>Plug and Play</td>
</tr>
<tr>
    <td><b>Model</b></td>
    <td>AH591Z</td>
</tr>
<tr>
    <td><b>Date</b></td>
    <td>02.04.2012</td>
</tr>
<tr>
    <td><b>Name</b></td>
    <td>CryptMachine</td>
</tr>
<tr>
    <td><b>ID</b></td>
    <td>9283</td>
</tr>
</table>

How would I for example get the Model, Name and ID but ignore the date and type, because I don't need those values.

Is there a smart way to do this with phpQuery? So far I've just played around with the phpQuery library, but i definitely got the basics down, I just cannot wrap my brain around this.


Solution

  • I haven't tested this, but something like this maybe?

    $doc = phpQuery::newDocumentHTML($theDocument);
    $table = $doc["table"];
    $model = pq($table)->find("tr:eq(1) td:eq(1)")->text();
    $id = pg($table)->find("tr:eq(4) td:eq(1)")->text();
    

    If there is more than one table on the page, you may have to use eq(n) to specify which one, remember that they are enumerated from 0, not 1.

    UPDATE: If you don't know the order of the rows, you could use something like this (again, untested, sorry, but should get your pointed in the right direction)

    <?php
    
    function getValue($table, $label) {
        $lable = strtolower($label);
        $rows = pq('tr', $table);
    
        foreach($rows as $row):
            if ( strtolower(pq($row)->find('td:eq(0)').text() ) === $label ):
                return pq($row)->find('td:eq(1)').text();
            endif;
        endforeach;
    }
    
    $doc = phpQuery::newDocumentHTML($theDocument);
    $table = $doc["table"];
    
    $model = getValue($table, "Model");
    $id = getValue($table, "ID");
    
    ?>