我使用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 ....”等。 有什么想法吗?
答案 0 :(得分:3)
这将有效
foreach($html->find('table') as $table){
// returns all the <tr> tag inside $table
$all_trs = $table->find('tr');
$count = count($all_trs);
echo $count;
}
答案 1 :(得分:0)
我正在研究这个问题一段时间,但是有人打败了我。我的解决方案并不优雅,但是如果你想放弃使用任何库,你可以在本地编写相同的东西。
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.");
}
}
}
答案 2 :(得分:0)
如果您有与该表关联的数据库,则可以使用以下代码:
`$ result = mysql_query(“ SELECT * FROM table1”,$ link); $ num_rows = mysql_num_rows($ result);
回显“ $ num_rows行\ n”; `
答案 3 :(得分:0)
为什么不为此使用简单的计数变量?
$count = 0;
foreach($res as $value){
$count++;
}