0

I am having trouble parsing a table with PHP Simple HTML DOM Parser 1.81 from SourceForge. I have PHP 7.1. I made this test to explain my problem.

I have this html file test.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <div class="workers">
            <table>
                <tr>
                    <td>Bob</td>
                    <td>Plumber</td>
                </tr>
                <tr>
                    <td>Jane</td>
                    <td>Lawyer</td>
                </tr>
            </table>
        </div>
    </body>
</html>

Here is my PHP code:

<?php
require('simple_html_dom.php');
// Create DOM from URL or file
$html = file_get_html('test.html');

// creating an array of elements
    $table = $html->find('table',0);

    foreach($table->find('tr') as $row) {

        $rowKey = $row->find('td',0)->plaintext;

        var_dump($row_key);

        $value = $row->find('td',1)->plaintext;

        var_dump($value);

        echo "rowkey=".$rowkey;
        echo "value=".$value;
        echo "<br>";
    } 
?>

I am having trouble getting the value of the first td for a row called $rowkey in my example. It is returning null.

I would appreciate any help or advice. Thank you.

1

1 Answer 1

1

You appear to be using rowKey, row_key and rowkey. My advice would be to pick one variable name and stick to it :-)

More seriously, neither the var_dump nor the echo will use the variable you set to hold the DOM reference. Instead, they'll use some other value which appears to be, in this case, an uninitialised one.

If you change them all to be rowKey (or another if you prefer), it should work fine.

2
  • The row_key error is just in the test. It does not explain why the rowkey at the end does not have a value. I changed row_key to rowkey and it is still not working. Jan 17, 2019 at 18:41
  • @user1964612, even if you changed it to rowkey, that is NOT the same as rowKey (with a capital K). As suggested, use ONE variable name.
    – paxdiablo
    Jan 18, 2019 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.