I have written a code in php to read from a csv file, print it and count the number of lines. Now I also need to find the number of records.
<?php
$c =0;
$fp = fopen("teksti.csv","r");
while(!feof($fp)){
$content = fgets($fp);
print_r ($content);
if($content)
$c++;
}
fclose($fp);
echo $c;?>
Use fgetcsv()
instead of fgets()
. This will parse the row into fields and return an array. Then you can use count()
to get the number of elements, and add this to a total.
<?php
$rows = 0;
$cells = 0;
$fp = fopen("teksti.csv","r");
while($content = fgetcsv($fp)){
print_r ($content);
$rows++;
$cells += count($content);
}
fclose($fp);
echo "Total rows = $rows, total cells = $cells";
?>