[英]Count the rows in a html table using php
我正在使用htmldomparsing
循環瀏覽 html 文件以尋找表格,例如
foreach($html->find('table') as $table)
{
foreach($table->find('tr') as $tr)
{
$count = count($tr);
$test = explode(" ",$count);
echo $count;
}
}
我正在嘗試計算表中的行數,但每次使用count function
它都會返回: 1111111
等。
在計算行數時,有什么方法可以計算每一行並且計數會增加而不是拋出“1111 ....”等任何想法?
這將工作
foreach($html->find('table') as $table){
// returns all the <tr> tag inside $table
$all_trs = $table->find('tr');
$count = count($all_trs);
echo $count;
}
如果您有一個與該表關聯的數據庫,則可以使用以下代碼:
`$result = mysql_query("SELECT * FROM table1", $link); $num_rows = mysql_num_rows($result);
echo "$num_rows 行\\n"; `
為什么不使用一個簡單的計數變量呢?
$count = 0;
foreach($res as $value){
$count++;
}
我在這方面工作了一段時間,但有人打敗了我。 我的解決方案並不優雅,但如果您想擺脫使用任何庫,您可以在本地編寫相同的內容。
function count_tr($data, $p=0)
{
//$data is a string that we assume to have some html in it.
//$p is an indicator of where we are in the string
//$table_counts is an array of numRows
//$numRows is the number of rows we've counted this table
//$z is an indicator of where the next </table> tag is
$numRows = 0;
$table_counts = array();
$z = $p;
//First lets loop through it until we find a <table tag
while($p < strlen($data))
{
//we will break under the condition that we have found the end of the data
//If table is found, count its <tr tags. Else, break
if($p = strpos("<table", $data, $p) != FALSE)
{
//if we find a </table tag we want to know where it is.
//else we need to stop execution.
if($z = strpos("</table", $data, $p) != FALSE)
{
$numRows = 0;
while($p < strlen($data))
{
//find the position of the next <tr
if($p=strpos("<tr", $data, $p) != FALSE)
{
//if the <tr tag is within this <table tag then we count it
//else we break to the next iteration
if($p<$z)
{
$numRows++;
}
else
{
//This will take us to the next <table iteration.
break;
}
}
}
$table_counts[] = $numRows;
}
else
{
die("The data is not formatted correctly. That is beyond the scope of this snipped. Please write a validation script.");
}
}
else
{
die("There is not a <table tag.");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.