Skip to content

Instantly share code, notes, and snippets.

Last active September 28, 2022 10:34
Show Gist options
  • Save josephspurrier/8780545 to your computer and use it in GitHub Desktop.
Save josephspurrier/8780545 to your computer and use it in GitHub Desktop.
Parse a CSV file in PHP, remove hidden characters, escape fields to prepare for MySQL, and return an associative array.
// Auto detect line endings
ini_set('auto_detect_line_endings', true);
function loadCSV($file)
// Create an array to hold the data
$arrData = array();
// Create a variable to hold the header information
$header = NULL;
// Connect to the database
//$db = mysqli_connect('localhost','username','password','test') or die("Failed to connect to MySQL: " . mysqli_connect_error());
// If the file can be opened as readable, bind a named resource
if (($handle = fopen($file, 'r')) !== FALSE)
// Loop through each row
while (($row = fgetcsv($handle)) !== FALSE)
// Loop through each field
foreach($row as &$field)
// Remove any invalid or hidden characters
$field = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $field);
// Escape characters for MySQL (single quotes, double quotes, linefeeds, etc.)
//$field = mysqli_escape_string($db, $field);
// If the header has been stored
if ($header)
// Create an associative array with the data
$arrData[] = array_combine($header, $row);
// Else the header has not been stored
// Store the current row as the header
$header = $row;
// Close the file pointer
// Close the MySQL connection
return $arrData;
// Load the CSV and return an associative array
$data = loadCSV('test.csv');
// Output the contents of the array
Copy link

kaanuki commented May 15, 2017

This worked great for me! Thanks Joseph - I had a a csv that was a real trouble maker, and this solved the issue. However, I cant get the '$header' to work - its not being generated. What am I missing?

Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment