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";
}
?>
source to share
There are several problems with this code:
- To load from HTML file, you need to use
DOMDocument::loadHTMLFile()
, notloadHTML()
how you did it. Use$dom->loadHTMLFile("figures.html")
. - You cannot use
getElementsByTagName()
onDOMNodeList
as you did (on$table
). It can only be used onDOMDocument
.
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.
source to share
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
source to share