Number of Columns and Rows in CSV using php

How to get the # of columns and rows from a csv using php
[Can be useful when parsing a csv, e.g: creating a table in a database from a csv - need to know # of columns]

2 ways

//using FGETCSV

$myFile = "THEFILE.csv";

$row = 0;
if (($handle = fopen($myFile , "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
    }        echo  "Columns = $num"."<br>";
         echo  "Rows = $row";
    fclose($handle);
}

//Just using FOPEN
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$theData2 = explode ( "\n", $theData);
fclose($fh);

$r2=-1;

$col = $theData2[0];
$piece = explode(",",$col);
$c2  = count($piece);

foreach($theData2 as $line){
 $r2++;
}
    echo  "Columns = $c2 <br>";
         echo  "Rows = $r2";

No Comments to “Number of Columns and Rows in CSV using php”  

  1. No Comments

Leave a Reply