Solution 1 :

You need another loop of $cols, and then you need to get the contents of the node to echo it.

foreach($rows as $row)
    $cols = $row->getElementsByTagName('td');
    foreach ($cols as $col) {
        echo $col->textContent;

Problem :

I’m currently working on a program that’ll run through an HTML file and grab the contents of the tables inside–so I can turn those tables into a json format. Currently I’m having trouble getting the tables out of the HTML code. I was wondering what I was doing wrong–this is the code I am currently using. I am getting an error(posting the error off at the bottom.)

$data = file_get_contents('C:xampphtdocstext.html');

$dom = new domDocument;

$dom->preserveWhitespace =false;

$tables =$dom->getElementsByTagName('table');

$rows = $tables->item(1)->getElementsByTagName('tr');

foreach($rows as $rows)
    $cols = $rows->getElementsByTagName('td');
    echo $cols; //getting error here.

The error I’m getting is:
Fatal error: Uncaught Error: Object of class DOMNodeList could not be converted to string in C:xampphtdocsparser.php:28 Stack trace: #0 {main} thrown in C:xampphtdocsparser.php on line 28


Comment posted by El_Vanja

First rule of

Comment posted by El_Vanja

Secondly, a tip for a good question: “I’m having trouble getting the tables” is very vague. Always describe as precisely as you can; which exact part is failing and in what way (error or undesired value).

Comment posted by Gfellha

@El_Vanja so should it be $rows as row then?

Comment posted by Gfellha

@El_Vanja I added some more clarification on to where my issue was–thank you for bringing that up.

Comment posted by El_Vanja

Well, the error is pretty clear. You cannot echo something that can’t be turned into a string. If you just want to quickly see what you’re getting, use