• # Dans la même famille, ouvrir et décoder si besoin, en zappant le BOM

    Posté par (site web personnel) . En réponse au message Recherche de BOM dans un site. Évalué à 1.

    <?php
    /*
     * This function was unshamefully stolen and modified from the following blog post :
     * http://www.practicalweb.co.uk/blog/08/05/18/reading-unicode-(...)
     */
    function fopen_utf8($filename, $mode){
     $encoding='';
     $handle = fopen($filename, $mode);
     
     $bom = fread($handle, 2);
     $bom_size = 0;
     if($bom === chr(0xff).chr(0xfe) || $bom === chr(0xfe).chr(0xff)){
     // UTF16 Byte Order Mark present
     $encoding = 'UTF-16';
    	 $bom_size = 2;
     } else {
     if( $bom_size == 0 ){
     rewind($handle);
    	 $bom = fread($handle, 3);
    	 if($bom === chr(0xef).chr(0xbb).chr(0xbf) ){
    	 // UTF8 marker, not really byte order mark, present
    	 $encoding = 'UTF-8';
    	 $bom_size = 3;
    	 }else{
    	 rewind($handle);
    	 $file_sample = fread($handle, 1000) + 'e'; //read first 1000 bytes
     // + e is a workaround for mb_string bug
     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');
     }
     
     fseek($handle, $bom_size);
     
     return $handle;
    }
    ?>