Last active
September 28, 2022 10:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.