Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
else
{
// Store the current row as the header
$header = $row;
}
}
// Close the file pointer
fclose($handle);
}
// Close the MySQL connection
//mysqli_close($db);
return $arrData;
}
// Load the CSV and return an associative array
$data = loadCSV('test.csv');
// Output the contents of the array
print_r($data);
@kaanuki

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.