Count total no of row in a table in PHP

Hi I am viewing xls table in php using below code. I want to count the no of row of the table below the line. But its not appearing the result. Result is showing O, but it should be 6. Please have a look & advise.

echo $table ="<table>";    
    $x=1; 
    while($x<=$connection->sheets[$sheet]['numRows']) { 
      echo "\t<tr>\n"; 
      $y=1; 
      while($y<=$connection->sheets[$sheet]['numCols']) { 
        $cell = isset($connection->sheets[$sheet]['cells'][$x][$y]) ? $connection->sheets[$sheet]['cells'][$x][$y] : ''; 
        echo "\t\t<td>$cell</td>\n";   
        $y++; 
      }   
      echo "\t</tr>\n"; 
      $x++; 
    }     
 echo "</table>";   
 $count = substr_count($table, "<tr>"); 
echo "Total rows: ".$count; 
echo "</br>";  
Here is the output.

here is the output.

Why don’t you just echo $x as that’s your row count?

In any case, the reason it isn’t working is because the only thing you do with $table is assign an opening table tag to it - the rest is just echoed directly to the screen. You need to append all the other output to it if you want this method to work, then echo it to produce the output.

Hi Thanks, I have done accordingly , but in result it shows 7 row, where i have 6 row,as you can see the image above.

Here is the code.

echo"<table>";
	$x=1;
    while($x<=$connection->sheets[$sheet]['numRows']) {
      echo "\t<tr>\n";
      $y=1;
      while($y<=$connection->sheets[$sheet]['numCols']) {
        $cell = isset($connection->sheets[$sheet]['cells'][$x][$y]) ? $connection->sheets[$sheet]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n";  
        $y++;
      }  
      echo "\t</tr>\n";
      $x++;
    }
 echo "</table>";  
echo "Total rows: ".$x;
echo "</br>";

You initialized $x = 1, so shouldn’t the row count be $x - 1?

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.