Number of Columns and Rows in CSV using php
Published March 10th, 2010 in PHP, Programming Tags: No Tags.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";
$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";
Categories |
||||
No Comments to “Number of Columns and Rows in CSV using php”
Please Wait
Leave a Reply