Thursday, January 05, 2012

PHP - Parsing a csv file created by Excel

Useful for updating tabular data on a website, without editing any html. Especially if there is no access to a database to upload the info. I found this function at php.net. It returns an array with all the data in the csv file...



function parse_csv($file,$comma=',',$quote='"',$newline="\n") {

$db_quote = $quote . $quote;

// Clean up file
$file = trim($file);
$file = str_replace("\r\n",$newline,$file);

$file = str_replace($db_quote,'"',$file); // replace double quotes with " HTML entities
$file = str_replace(',",',',,',$file); // handle ,"", empty cells correctly

$file .= $comma; // Put a comma on the end, so we parse last cell


$inquotes = false;
$start_point = 0;
$row = 0;

for($i=0; $i<strlen($file); $i++) {

$char = $file[$i];
if ($char == $quote) {
if ($inquotes) {
$inquotes = false;
}
else {
$inquotes = true;
}
}

if (($char == $comma or $char == $newline) and !$inquotes) {
$cell = substr($file,$start_point,$i-$start_point);
$cell = str_replace($quote,'',$cell); // Remove delimiter quotes
$cell = str_replace('"',$quote,$cell); // Add in data quotes
$data[$row][] = $cell;
$start_point = $i + 1;
if ($char == $newline) {
$row ++;
}
}
}
return $data;
}

$filename = "/path/to/file.csv";
$fd = fopen ($filename, "r");
$file = fread ($fd,filesize ($filename));


$new_array=parse_csv($file); // Returns an array of data from the csv file



Then the array can be used the same way a returned mysql result set would be used (see here). The array can be searched (see previous post here) or to simply access elements from the returned array you can simply call individual elements as such...


//line 1 data
echo $new_array[0][0];
echo $new_array[0][1];
echo $new_array[0][2];
//etc
//line 2 data
echo $new_array[1][0];
echo $new_array[1][1];
echo $new_array[1][2];
//etc


To pick out random lines from a csv (eg.with 3 columns year,day,month) and use that data the rand function can be used as follows...



$num=count($new_array);
$num=$num-1;//minus one to cope with 0 in array
$i=rand (0, $num );


$year=$new_array[$i][0];
$day=$new_array[$i][1];
$month=$new_array[$i][2];

echo "The random year is ".$year.". The random day is ".$day.". The random month is ".$month;

No comments: