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

I have a table like this:

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

      

And I want to get td content. But I couldn't do 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";
}
?>

      

+3


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

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

+6


source


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

eg



for($i=1;$i<=10;$i++){
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

0


source







All Articles