Last active
January 28, 2022 16:04
-
-
Save EduardoSP6/ce276874e66c93449ccd7b9a5066a134 to your computer and use it in GitHub Desktop.
PHP function to convert CSV file content to 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
<?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