Processing CSV file for web projects is very usefull to show CSV Upload list, Upload data to database table, processing bulk posting etc., Here is the function to process CSV file, using this function we can convert our CSV file to PHP Mufti dimensional Array
CSS to Array in PHP
# Desc: Function to Make PHP Array from CSV file data
# Parm: $csv_path,$header_row,$preserve_keys (usefull for Database Insert)
# Return: Array $output['header'], output['data'];
function csv_to_array($csv_file,$preserve_keys=FALSE,$header_row=TRUE)
{
$fp=fopen($csv_file,"r",true);
while (!feof($fp)) {
$data[]=explode(",",fgets($fp, 1024));
}
// Get Field Header and Unset field row from data
if($header_row){
// Preserve Keys or Make array Keyas as Numberic
if($preserve_keys)
{
foreach($data[0] as $head){javascript:void(0)
$head=trim(($head));
$output['header'][$head]=ucwords($head);
}
}else
{
foreach($data[0] as $head){
$head=trim(($head));
$output['header'][]=ucwords($head);
}
}
unset($data[0]);
}
// Push data into data key;
$output['data']=$data;
//Return array output
return $output;
}
No comments:
Post a Comment