我正在使用domDocument计算html表中的行数。这是我的代码
if(isset($_POST['List']) && $_POST['List'] == true)
{
$data = file_get_contents('File.php');
$dom = new domDocument;
@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$table = $dom->getElementById('Table');
$rows = substr_count($table, "<tr>");
for($x=0;$x<$rows;$x++)
{
}
}
单步执行代码,$ rows为null。 这是$ table
的内容tagName:"table"
schemaTypeInfo:null
nodeName:"table"
nodeValue:"\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tCategoryAMA1A2ABBECCEC1C1EDDED1D1EW\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t"
nodeType:1
parentNode:"(object value omitted)"
childNodes:"(object value omitted)"
firstChild:"(object value omitted)"
lastChild:"(object value omitted)"
previousSibling:"(object value omitted)"
nextSibling:null
attributes:"(object value omitted)"
ownerDocument:"(object value omitted)"
namespaceURI:null
prefix:""
localName:"table"
baseURI:null
textContent:"\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tCategoryAMA1A2ABBECCEC1C1EDDED1D1EW\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t"
我已更改代码如下
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$doc = new domDocument();
@$doc->loadHTMLFile($url);
$table = $doc->getElementById('Table');
$rows = $table->getElementsByTagName('tr');
$count = count($rows);
我在表格中提交了2行表格,但计数为1。 这是$ table
的内容tagName:"table"
schemaTypeInfo:null
nodeName:"table"
nodeValue: "\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tCategoryAMA1A2ABBECCEC1C1EDDED1D1EW\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tDate\r\n\t\t\t\t\t\t"
nodeType:1
parentNode:"(object value omitted)"
childNodes:"(object value omitted)"
firstChild:"(object value omitted)"
lastChild:"(object value omitted)"
previousSibling:"(object value omitted)"
nextSibling:null
attributes:"(object value omitted)"
ownerDocument:"(object value omitted)"
namespaceURI:null
prefix:""
localName:"table"
baseURI:null
textContent: "\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tCategoryAMA1A2ABBECCEC1C1EDDED1D1EW\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tDate\r\n\t\t\t\t\t\t"
loadHTMLFile是否与file_get_contents具有相同的限制,只看到原始的html?
答案 0 :(得分:1)
选择表格后,您可以使用getElementsByTagName
获取其行。
$rows = $table->getElementsByTagName('tr');
结果将是DOMNodeList
对象,其length
属性应该是您正在寻找的计数。
echo $rows->length;
看起来您只是使用行计数来设置for循环,这可能不是必需的,因为您可以使用foreach迭代这组行。
foreach ($rows as $row) {
// do something with the row
}