Skip to content

Instantly share code, notes, and snippets.

@seanburlington
Last active March 31, 2020 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanburlington/1238ffbd56db3b7c8d5b to your computer and use it in GitHub Desktop.
Save seanburlington/1238ffbd56db3b7c8d5b to your computer and use it in GitHub Desktop.
Function to open an Excel generated CSV using unicode
<?php
# http://www.practicalweb.co.uk/blog/2008/05/18/reading-a-unicode-excel-file-in-php/
function fopen_utf8($filename){
$encoding='';
$handle = fopen($filename, 'r');
$bom = fread($handle, 2);
// fclose($handle);
rewind($handle);
if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
// UTF16 Byte Order Mark present
$encoding = 'UTF-16';
} else {
$file_sample = fread($handle, 1000) //read first 1000 bytes
rewind($handle);
$encoding = mb_detect_encoding($file_sample , 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
}
if ($encoding){
stream_filter_append($handle, 'convert.iconv.'.$encoding.'/UTF-8');
}
return ($handle);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment