How can i get td values โ€‹โ€‹using dom and php

I have a table like this:



And I want to get td content. But I couldn't do it.

$dom = new DOMDocument();
$table = $dom->getElementsByTagName('table');

foreach ($tds as $t){
   echo $t->nodeValue, "\n";



source to share

2 answers

There are several problems with this code:

  • To load from HTML file, you need to use DOMDocument::loadHTMLFile()

    , not loadHTML()

    how you did it. Use $dom->loadHTMLFile("figures.html")

  • You cannot use getElementsByTagName()

    on DOMNodeList

    as you did (on $table

    ). It can only be used on DOMDocument


You can do something like this:

$dom = new DOMDocument();
$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 can simply find all elements with a tag name td

(although I'm sure you want to do this with a table.



You have to use a for loop to display multiple td's

c attributes in it id

, so each td

must mean different id

in the html file


echo "<td id ='id_".$i."'>".$tdvalue."</td>";


and then again you can get the values td

just by iterating over the other to loop throughgetElementById



All Articles