-
-
Save kaanuki/528a39d29a6856ebb642afb5a6297afc 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 hidden or 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