如何使用dom和php获取td值 [英] How can I get td values using dom and php
本文介绍了如何使用dom和php获取td值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张这样的表:
<table>
<tr>
<td>Values</td>
<td>5000</td>
<td>6000</td>
</tr>
</table>
我想得到td的内容。但是我无法管理它。
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";
}
?>
推荐答案
此代码有多个问题:
- 要从HTML文件加载,您需要使用
DOMDocument :: loadHTMLFile()
不如你所做的那样loadHTML()
使用$ dom-> loadHTMLFile(figures.html)
。 - 您不能使用
($ code> $ table
)上的DOMNodeList
中的getElementsByTagName()它只能在DOMDocument
中使用。
- To load from an HTML file, you need to use
DOMDocument::loadHTMLFile()
, notloadHTML()
as you have done. Use$dom->loadHTMLFile("figures.html")
. - You can't use
getElementsByTagName()
on aDOMNodeList
as you have done (on$table
). It can only be used on aDOMDocument
.
你可以做一些类似这个:
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";
}
}
或者,您可以直接搜索所有元素标签名称 td
(虽然我确信你想以表格的方式这样做。
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.
这篇关于如何使用dom和php获取td值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文