I making a script that takes to first line of a csv file (the headers) and dynamically makes them into the equivalent setter in a class that I created.
Ex. setFirst_name() is the setter in the class
My code would make first_name to look like the setter above as this:
$func = 'set'. ucfirst(trim($export_array[0][$key]));
Here is the first line of the csv file: medicaid_number,first_name,last_name, ...
Here is a var_dump() of a portion of the output:
/var/www/html/index.php:145:
string(21) "setmedicaid_number"
/var/www/html/index.php:145:
string(13) "setFirst_name"
/var/www/html/index.php:145:
string(12) "setLast_name"
/var/www/html/index.php:145:
... There is more, they are all OK
Here is the issue, the very first item (and only this item) medicaid_number
does not get uppercased. All the other items in array are modified just fine.
Could someone maybe explain why this is happening? or have a solution?
Thank you.
$file="client_export_data.csv";
$csv= file_get_contents($file);
$export_array = array_map("str_getcsv", explode("\n", $csv));
foreach($export_array as $lineKey => $line){
foreach($line as $key => $item){
$func = 'set'. ucfirst(trim($export_array[0][$key]));
var_dump($func);
}
die();
}
If you have UTF-8 with BOM, just add
$csv_header=str_replace("\xEF\xBB\xBF",'',$csv_header);
when you read the first line of your csv.
If there is some different encoding (UTF-16, UTF-32, etc) you can try some regex:
$csv_header=preg_replace("/[^a-z_,]/",'',$csv_header);