Можно ли конвертировать файл в UTF-8 на моем конце?
Если у меня есть доступ к файлу после подачи с
Замечания: Пользователь может загрузить файл CSV с любым типом кодировки, я обычно сталкиваюсь с неизвестный 8-битный кодировок.
Но проблема в том, что этот код удаляет специальные символы, такие как одинарные кавычки.
Я поставил это для дополнительной информации. Спасибо за тех, кто может помочь!
Решение
Попробуйте это.
Пример, который я использовал, был чем-то, что я делал в тестовой среде, возможно, вам придется немного изменить код.
У меня был текстовый файл со следующими данными в:
Затем у меня была форма, в которую входил файл и выполнялся следующий код:
Функция neatify_files это то, что я написал, чтобы сделать $_FILES массив более логичен в своей компоновке.
Форма является стандартной формой, которая просто POST данные на сервер.
Примечание: использование $_SERVER["PHP_SELF"] это риск для безопасности, см здесь .
Когда данные публикуются, я сохраняю файл в переменной. Очевидно, что если вы используете multiple Атрибут ваш код будет выглядеть не совсем так.
$handle хранит все содержимое текстового файла в формате только для чтения; следовательно "r" аргумент.
$enc использует mb_detect_encoding функция для определения кодировки (дух).
Сначала у меня были проблемы с получением правильной кодировки. Настройка encoding_list использовать только UTF-8 и настройки strict чтобы быть правдой.
Если кодировка UTF-8, то я просто печатаю строку, если нет, я конвертирую ее в UTF-8, используя iconv функция.
Другие решения
прежде чем вы сможете конвертировать его в utf-8, вам нужно знать, что это за набор символов.
если вы не можете понять это, вы не можете каким-либо вменяемым образом преобразовать его в utf8 ..
однако безумный способ преобразовать его в utf-8, если кодировка не может быть определена,
это просто удалить любые байты, которые не являются действительными в UTF-8, вы
может быть в состоянии использовать это как запасной вариант …
предупреждение, непроверенный код (я внезапно спешу), но может выглядеть примерно так:
Вы можете преобразовать текст файла в двоичные данные, используя следующие
после преобразования данных в двоичный файл вы просто изменяете текст на метод php mb_convert_encoding ($ fileText, «UTF-8»);
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
mb_convert_encoding — Преобразует кодировку символов
Описание
Преобразует символы val в кодировку to_encoding . Также можно указать необязательный параметр from_encoding . Если val является массивом ( array ), все его строковые ( string ) значения будут преобразованы рекурсивно.
Список параметров
Строка ( string ) или массив ( array ), для преобразования.
Кодировка, в которую будут преобразованы данные из val .
Параметр для указания исходной кодировки строки. Это может быть массив ( array ), или строка со списком кодировок через запятую. Если параметр from_encoding не указан, то кодировка определяется автоматически.
Возвращаемые значения
Преобразованная строка ( string ) или массив ( array ).
Примеры
Пример #1 Пример использования mb_convert_encoding()
/* Преобразует строку в кодировку SJIS */
$str = mb_convert_encoding ( $str , "SJIS" );
/* Преобразует из EUC-JP в UTF-7 */
$str = mb_convert_encoding ( $str , "UTF-7" , "EUC-JP" );
/* Автоматически определяется кодировка среди JIS, eucjp-win, sjis-win, затем преобразуется в UCS-2LE */
$str = mb_convert_encoding ( $str , "UCS-2LE" , "JIS, eucjp-win, sjis-win" );
/* "auto" используется для обозначения "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding ( $str , "EUC-JP" , "auto" );
?>
Смотрите также
- mb_detect_order() — Установка/получение списка кодировок для механизмов определения кодировки
Список изменений
Версия | Описание |
---|---|
7.2.0 | Функция теперь также принимает массив ( array ) в val . Ранее поддерживались только строки ( string ). |
User Contributed Notes 32 notes
For my last project I needed to convert several CSV files from Windows-1250 to UTF-8, and after several days of searching around I found a function that is partially solved my problem, but it still has not transformed all the characters. So I made this:
function w1250_to_utf8($text) <
// map based on:
// http://konfiguracja.c0.pl/iso02vscp1250en.html
// http://konfiguracja.c0.pl/webpl/index_en.html#examp
// http://www.htmlentities.com/html/entities/
$map = array(
chr(0x8A) => chr(0xA9),
chr(0x8C) => chr(0xA6),
chr(0x8D) => chr(0xAB),
chr(0x8E) => chr(0xAE),
chr(0x8F) => chr(0xAC),
chr(0x9C) => chr(0xB6),
chr(0x9D) => chr(0xBB),
chr(0xA1) => chr(0xB7),
chr(0xA5) => chr(0xA1),
chr(0xBC) => chr(0xA5),
chr(0x9F) => chr(0xBC),
chr(0xB9) => chr(0xB1),
chr(0x9A) => chr(0xB9),
chr(0xBE) => chr(0xB5),
chr(0x9E) => chr(0xBE),
chr(0x80) => ‘€’,
chr(0x82) => ‘‚’,
chr(0x84) => ‘„’,
chr(0x85) => ‘…’,
chr(0x86) => ‘†’,
chr(0x87) => ‘‡’,
chr(0x89) => ‘‰’,
chr(0x8B) => ‘‹’,
chr(0x91) => ‘‘’,
chr(0x92) => ‘’’,
chr(0x93) => ‘“’,
chr(0x94) => ‘”’,
chr(0x95) => ‘•’,
chr(0x96) => ‘–’,
chr(0x97) => ‘—’,
chr(0x99) => ‘™’,
chr(0x9B) => ‘’’,
chr(0xA6) => ‘¦’,
chr(0xA9) => ‘©’,
chr(0xAB) => ‘«’,
chr(0xAE) => ‘®’,
chr(0xB1) => ‘±’,
chr(0xB5) => ‘µ’,
chr(0xB6) => ‘¶’,
chr(0xB7) => ‘·’,
chr(0xBB) => ‘»’,
);
return html_entity_decode(mb_convert_encoding(strtr($text, $map), ‘UTF-8’, ‘ISO-8859-2’), ENT_QUOTES, ‘UTF-8’);
>
I’ve been trying to find the charset of a norwegian (with a lot of ø, æ, å) txt file written on a Mac, i’ve found it in this way:
= "A strange string to pass, maybe with some ø, æ, å characters." ;
foreach( mb_list_encodings () as $chr ) <
echo mb_convert_encoding ( $text , ‘UTF-8’ , $chr ). " : " . $chr . "
" ;
>
?>
The line that looks good, gives you the encoding it was written in.
Hope can help someone
aaron, to discard unsupported characters instead of printing a ?, you might as well simply set the configuration directive:
in your php.ini. Be sure to include the quotes around none. Or at run-time with
Hey guys. For everybody who’s looking for a function that is converting an iso-string to utf8 or an utf8-string to iso, here’s your solution:
public function encodeToUtf8($string) <
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
>
public function encodeToIso($string) <
return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
>
For me these functions are working fine. Give it a try
many people below talk about using
( $s , ‘HTML-ENTITIES’ , ‘UTF-8’ );
?>
to convert non-ascii code into html-readable stuff. Due to my webserver being out of my control, I was unable to set the database character set, and whenever PHP made a copy of my $s variable that it had pulled out of the database, it would convert it to nasty latin1 automatically and not leave it in it’s beautiful UTF-8 glory.
So [insert korean characters here] turned into .
I found myself needing to pass by reference (which of course is deprecated/nonexistent in recent versions of PHP)
so instead of
(& $s , ‘HTML-ENTITIES’ , ‘UTF-8’ );
?>
which worked perfectly until I upgraded, so I had to use
( ‘mb_convert_encoding’ , array(& $s , ‘HTML-ENTITIES’ , ‘UTF-8’ ));
?>
Hope it helps someone else out
My solution below was slightly incorrect, so here is the correct version (I posted at the end of a long day, never a good idea!)
Again, this is a quick and dirty solution to stop mb_convert_encoding from filling your string with question marks whenever it encounters an illegal character for the target encoding.
function convert_to ( $source , $target_encoding )
<
// detect the character encoding of the incoming file
$encoding = mb_detect_encoding ( $source , "auto" );
// escape all of the question marks so we can remove artifacts from
// the unicode conversion process
$target = str_replace ( "?" , "[question_mark]" , $source );
// convert the string to the target encoding
$target = mb_convert_encoding ( $target , $target_encoding , $encoding );
// remove any question marks that have been introduced because of illegal characters
$target = str_replace ( "?" , "" , $target );
// replace the token string "[question_mark]" with the symbol "?"
$target = str_replace ( "[question_mark]" , "?" , $target );
return $target ;
>
?>
Hope this helps someone! (Admins should feel free to delete my previous, incorrect, post for clarity)
-A
To add to the Flash conversion comment below, here’s how I convert back from what I’ve stored in a database after converting from Flash HTML text field output, in order to load it back into a Flash HTML text field:
function htmltoflash($htmlstr)
<
return str_replace("
","
",
str_replace(" ",">",
mb_convert_encoding(html_entity_decode($htmlstr),
"UTF-8","ISO-8859-1"))));
>
Why did you use the php html encode functions? mbstring has it’s own Encoding which is (as far as I tested it) much more usefull:
$text = mb_convert_encoding($text, ‘HTML-ENTITIES’, "UTF-8");
instead of ini_set(), you can try this
For those wanting to convert from $set to MacRoman, use iconv():
= iconv ( ‘UTF-8’ , ‘macintosh’ , $string );
?>
(‘macintosh’ is the IANA name for the MacRoman character set.)
If you are trying to generate a CSV (with extended chars) to be opened at Exel for Mac, the only that worked for me was:
( $CSV , ‘Windows-1252’ , ‘UTF-8’ ); ?>
I also tried this:
//Separado OK, chars MAL
iconv ( ‘MACINTOSH’ , ‘UTF8’ , $CSV );
//Separado MAL, chars OK
chr ( 255 ). chr ( 254 ). mb_convert_encoding ( $CSV , ‘UCS-2LE’ , ‘UTF-8’ );
?>
But the first one didn’t show extended chars correctly, and the second one, did’t separe fields correctly
Clean a string for use as filename by simply replacing all unwanted characters with underscore (ASCII converts to 7bit). It removes slightly more chars than necessary. Hope its useful.
// convert UTF8 to DOS = CP850
//
// $utf8_text=UTF8-Formatted text;
// $dos=CP850-Formatted text;
$dos = mb_convert_encoding($utf8_text, "CP850", mb_detect_encoding($utf8_text, "UTF-8, CP850, ISO-8859-15", true));
Another sample of recoding without MultiByte enabling.
(Russian koi->win, if input in win-encoding already, function recode() returns unchanged string)
// 0 — win
// 1 — koi
function detect_encoding ( $str ) <
$win = 0 ;
$koi = 0 ;
if( $win $koi ) <
return 1 ;
> else return 0 ;
// recodes koi to win
function koi_to_win ( $string ) <
$kw = array( 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , 151 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 254 , 224 , 225 , 246 , 228 , 229 , 244 , 227 , 245 , 232 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 255 , 240 , 241 , 242 , 243 , 230 , 226 , 252 , 251 , 231 , 248 , 253 , 249 , 247 , 250 , 222 , 192 , 193 , 214 , 196 , 197 , 212 , 195 , 213 , 200 , 201 , 202 , 203 , 204 , 205 , 206 , 207 , 223 , 208 , 209 , 210 , 211 , 198 , 194 , 220 , 219 , 199 , 216 , 221 , 217 , 215 , 218 );
$wk = array( 128 , 129 , 130 , 131 , 132 , 133 , 134 , 135 , 136 , 137 , 138 , 139 , 140 , 141 , 142 , 143 , 144 , 145 , 146 , 147 , 148 , 149 , 150 , 151 , 152 , 153 , 154 , 155 , 156 , 157 , 158 , 159 , 160 , 161 , 162 , 163 , 164 , 165 , 166 , 167 , 168 , 169 , 170 , 171 , 172 , 173 , 174 , 175 , 176 , 177 , 178 , 179 , 180 , 181 , 182 , 183 , 184 , 185 , 186 , 187 , 188 , 189 , 190 , 191 , 225 , 226 , 247 , 231 , 228 , 229 , 246 , 250 , 233 , 234 , 235 , 236 , 237 , 238 , 239 , 240 , 242 , 243 , 244 , 245 , 230 , 232 , 227 , 254 , 251 , 253 , 255 , 249 , 248 , 252 , 224 , 241 , 193 , 194 , 215 , 199 , 196 , 197 , 214 , 218 , 201 , 202 , 203 , 204 , 205 , 206 , 207 , 208 , 210 , 211 , 212 , 213 , 198 , 200 , 195 , 222 , 219 , 221 , 223 , 217 , 216 , 220 , 192 , 209 );
$end = strlen ( $string );
$pos = 0 ;
do <
$c = ord ( $string [ $pos ]);
if ( $c > 128 ) <
$string [ $pos ] = chr ( $kw [ $c — 128 ]);
>
function recode ( $str ) <
$enc = detect_encoding ( $str );
if ( $enc == 1 ) <
$str = koi_to_win ( $str );
>
Is it possible to convert a file into UTF-8 on my end?
If I have an access on the file after the submission with
Note: The user can upload a CSV file with any kind of charset, I usually encounter an unknown 8-bit charset.
But the problem is, this code remove special characters like single quote.
I put it for additional information. Thanks for those who can help!
5 Answers 5
Try this out.
The example I have used was something I was doing in a test environment, you might need to change the code slightly.
I had a text file with the following data in:
Then I had a form which took a file input in and performed the following code:
The function neatify_files is something I wrote to make the $_FILES array more logical in its layout.
The form is a standard form that simply POST s the data to the server.
Note: Using $_SERVER["PHP_SELF"] is a security risk, see here for more.
When the data is posted I store the file in a variable. Obviously, if you are using the multiple attribute your code won’t look quite like this.
$handle stores the entire contents of the text file, in a read-only format; hence the "r" argument.
$enc uses the mb_detect_encoding function to detect the encoding (duh).
At first I was having trouble with obtaining the correct encoding. Setting the encoding_list to use only UTF-8, and setting strict to be true.
If the encoding is UTF-8 then I simply print the line, if it didn’t I converted it to UTF-8 using the iconv function.