Replace Funky Characters While Importing CSV

Sometimes uploaded text/csv file may have non-utf8 or other funky characters using the function below.

public static function processUploadedBundles($request)
	{
		$content = file_get_contents($request->file('uploadedFile')->getRealPath());
 
        $lines = explode(PHP_EOL, $content);
        $array = [];
        foreach ($lines as $line) {
            $arrayCsv = str_getcsv($line, ",");
            $arrayCsv = array_map(function($value){
                return preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $value);
            }, $arrayCsv);
            $array[] = $arrayCsv;
		}
 
		return $array;
	}
Share this article

Similar Posts