Skip to content

Instantly share code, notes, and snippets.

@mmohiudd
Last active October 7, 2018 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmohiudd/5777780 to your computer and use it in GitHub Desktop.
Save mmohiudd/5777780 to your computer and use it in GitHub Desktop.
Basic CSV parse function
function getCSVData($file){
$info = pathinfo($file);
$fp = @fopen($file, "r");
$data = array();
$line = fgets($fp, 4096); // read the first line, headers
// use /[ "\']+/ to remove white spaces as well
$fields = preg_replace('/[ "\']+/', '', explode(",", trim($line)));
while (!feof($fp)) { // loop till end of file.
$line = fgets($fp, 4096); // read a line.
if (empty($line)) continue;
$field_values = array(); // will save all field values
$values = explode(",", trim($line));
$entry = array();
// only to sanitize the values
foreach($values as $i=>$value){ // fetch all value
$entry[$fields[$i]] = trim(str_replace('"', '', $value));
}
$data[] = $entry;
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment