Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active January 28, 2022 16:04
Show Gist options
  • Save EduardoSP6/ce276874e66c93449ccd7b9a5066a134 to your computer and use it in GitHub Desktop.
Save EduardoSP6/ce276874e66c93449ccd7b9a5066a134 to your computer and use it in GitHub Desktop.
PHP function to convert CSV file content to array
<?php
function csvToArray($filename = '', $delimiter = '\t')
{
if (!file_exists($filename) || !is_readable($filename))
return [];
$row = 0;
$fileContent = [];
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 5000, "\r")) !== FALSE) {
$line = utf8_encode(trim($data[0]));
if ($line) {
$fileContent[$row] = explode("\t", $line);
$row++;
}
}
fclose($handle);
}
$data = [];
if (count($fileContent) > 0) {
$totalRows = count($fileContent) - 1;
for ($i = 1; $i <= $totalRows; $i++) {
foreach($fileContent[0] as $value) {
$header = remove_accents($value);
$strHeader = str_replace(';', '--', $header);
$valueKeyColuna = explode("--", $strHeader);
$keyHeader = str_replace("\"", "", $valueKeyColuna);
}
foreach($fileContent[$i] as $valueName) {
$strReplace = str_replace('; ', '-', $valueName);
$str = str_replace(';', '--', $strReplace);
$valueKeyName = explode("--", $str);
$keyHeaderName = str_replace("\"", "", $valueKeyName);
}
$combined = array_combine($keyHeader, $keyHeaderName);
if (is_array($combined)) {
$data[] = $combined;
}
}
}
return $data;
}
function remove_accents($text)
{
$array1 = array( "á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"
, "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç","aâ‡");
$array2 = array( "a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"
, "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C","ç");
return strtolower(str_replace($array1, $array2, $text));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment