使用PHP解析html并遍历表行和列? [英] Parse html using PHP and loop through table rows and columns?
本文介绍了使用PHP解析html并遍历表行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从loadHTML解析HTML,但是遇到了麻烦,我设法遍历了文档中的所有< tr>
s,但是我没有我不知道如何遍历每行的< td>
。
I'm trying to parse HTML from loadHTML but I'm having trouble, I managed to loop through all <tr>
s in the document but I don't know how to loop through the <td>
s on each row.
这就是我所做的远:
$DOM->loadHTML($url);
$rows= $DOM->getElementsByTagName('tr');
for ($i = 0; $i < $rows->length; $i++) { // loop through rows
// loop through columns
...
}
如何遍历每一行的列?
推荐答案
DOMElement
还支持 getElementsByTagName
:
$DOM = new DOMDocument();
$DOM->loadHTMLFile("file path or url");
$rows = $DOM->getElementsByTagName("tr");
for ($i = 0; $i < $rows->length; $i++) {
$cols = $rows->item($i)->getElementsbyTagName("td");
for ($j = 0; $j < $cols->length; $j++) {
echo $cols->item($j)->nodeValue, "\t";
// you can also use DOMElement::textContent
// echo $cols->item($j)->textContent, "\t";
}
echo "\n";
}
这篇关于使用PHP解析html并遍历表行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文