我正在使用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:"rntttttttrnttttttttCategoryAMA1A2ABBECCEC1C1EDDED1D1EWrntttttttrnttttttttrntttttt"
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:"rntttttttrnttttttttCategoryAMA1A2ABBECCEC1C1EDDED1D1EWrntttttttrnttttttttrntttttt"
我更改了代码如下
$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: "rntttttttrnttttttttCategoryAMA1A2ABBECCEC1C1EDDED1D1EWrntttttttrnttttttttrntttttttDaterntttttt"
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: "rntttttttrnttttttttCategoryAMA1A2ABBECCEC1C1EDDED1D1EWrntttttttrnttttttttrntttttttDaterntttttt"
loadHTMLFile 是否具有与file_get_contents相同的限制,只看到原始 html?
选择表后,可以使用 getElementsByTagName
获取其行。
$rows = $table->getElementsByTagName('tr');
结果将是一个具有 length
属性的 DOMNodeList
对象,该属性应该是您要查找的计数。
echo $rows->length;
看起来您只是使用行计数来设置 for 循环,这可能不是必需的,因为您可以使用 foreach 迭代行集。
foreach ($rows as $row) {
// do something with the row
}