Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get td values using dom and php

Tags:

dom

php

I have a table such this :

<table>
<tr>
    <td>Values</td>
    <td>5000</td>
    <td>6000</td>
</tr>
</table>

And I want to get td's content. But I could not manage it.

<?PHP
$dom = new DOMDocument();
$dom->loadHTML("figures.html"); 
$table = $dom->getElementsByTagName('table');
$tds=$table->getElementsByTagName('td');

foreach ($tds as $t){
   echo $t->nodeValue, "\n";
}
?>
like image 400
mustafa Avatar asked Dec 27 '25 16:12

mustafa


1 Answers

There are multiple problems with this code:

  1. To load from an HTML file, you need to use DOMDocument::loadHTMLFile(), not loadHTML() as you have done. Use $dom->loadHTMLFile("figures.html").
  2. You can't use getElementsByTagName() on a DOMNodeList as you have done (on $table). It can only be used on a DOMDocument.

You could do something like this:

$dom = new DOMDocument();
$dom->loadHTMLFile("figures.html");
$tables = $dom->getElementsByTagName('table');

// Find the correct <table> element you want, and store it in $table
// ...

// Assume you want the first table
$table = $tables->item(0);

foreach ($table->childNodes as $td) {
  if ($td->nodeName == 'td') {
    echo $td->nodeValue, "\n";
  }
}

Alternatively, you could just directly search for all elements with tag name td (though I'm sure you want to do that in a table-specific manner.

like image 58
Milind Ganjoo Avatar answered Dec 30 '25 06:12

Milind Ganjoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!