Win 1251 to utf 8 in php

Php windows 1251 utf 8 iconv utf

Если добавить к out_charset строку //TRANSLIT , включается режим транслитерации. Это значит, что в случае, если символ не может быть представлен в требуемой кодировке, он будет заменен на один или несколько наиболее близких по внешнему виду символов. Если добавить строку //IGNORE , то символы, которые не могут быть представлены в требуемой кодировке, будут удалены. В случае отсутствия вышеуказанных параметров будет сгенерирована ошибка уровня E_NOTICE , а функция вернет FALSE . Как будет работат //TRANSLIT и будет ли вообще, зависит от системной реализации iconv() ( ICONV_IMPL ). Известны некоторые реализации, которые просто игнорируют //TRANSLIT , так что конвертация для символов некорректных для out_charset скорее всего закончится ошибкой. Строка, которую необходимо преобразовать.

Возвращаемые значения

Примеры

Пример #1 Пример использования iconv() echo ‘Исходная строка : ‘ , $text , PHP_EOL ;
echo ‘С добавлением TRANSLIT : ‘ , iconv ( «UTF-8» , «ISO-8859-1//TRANSLIT» , $text ), PHP_EOL ;
echo ‘С добавлением IGNORE : ‘ , iconv ( «UTF-8» , «ISO-8859-1//IGNORE» , $text ), PHP_EOL ;
echo ‘Обычное преобразование : ‘ , iconv ( «UTF-8» , «ISO-8859-1» , $text ), PHP_EOL ; Результатом выполнения данного примера будет что-то подобное:

User Contributed Notes 39 notes

The «//ignore» option doesn’t work with recent versions of the iconv library. So if you’re having trouble with that option, you aren’t alone. That means you can’t currently use this function to filter invalid characters. Instead it silently fails and returns an empty string (or you’ll get a notice but only if you have E_NOTICE enabled). This has been a known bug with a known solution for at least since 2009 years but no one seems to be willing to fix it (PHP must pass the -c option to iconv). It’s still broken as of the latest release 5.4.3. [UPDATE 15-JUN-2012]
Here’s a workaround. ini_set(‘mbstring.substitute_character’, «none»);
$text= mb_convert_encoding($text, ‘UTF-8’, ‘UTF-8’); That will strip invalid characters from UTF-8 strings (so that you can insert it into a database, etc.). Instead of «none» you can also use the value 32 if you want it to insert spaces in place of the invalid characters. Please note that iconv(‘UTF-8’, ‘ASCII//TRANSLIT’, . ) doesn’t work properly when locale category LC_CTYPE is set to C or POSIX. You must choose another locale otherwise all non-ASCII characters will be replaced with question marks. This is at least true with glibc 2.5.

Читайте также:  Html landscape orientation css

Example:
( LC_CTYPE , ‘POSIX’ );
echo iconv ( ‘UTF-8’ , ‘ASCII//TRANSLIT’ , «Žluťoučký kůň\n» );
// ?lu?ou?k? k?? setlocale ( LC_CTYPE , ‘cs_CZ’ );
echo iconv ( ‘UTF-8’ , ‘ASCII//TRANSLIT’ , «Žluťoučký kůň\n» );
// Zlutoucky kun
?> Interestingly, setting different target locales results in different, yet appropriate, transliterations. For example: //some German
$utf8_sentence = ‘Weiß, Goldmann, Göbel, Weiss, Göthe, Goethe und Götz’ ; //UK
setlocale ( LC_ALL , ‘en_GB’ ); //transliterate
$trans_sentence = iconv ( ‘UTF-8’ , ‘ASCII//TRANSLIT’ , $utf8_sentence ); //gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL ;

//Germany
setlocale ( LC_ALL , ‘de_DE’ ); $trans_sentence = iconv ( ‘UTF-8’ , ‘ASCII//TRANSLIT’ , $utf8_sentence ); //gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ä = ae, ö = oe and ü = ue)
echo $trans_sentence . PHP_EOL ; to test different combinations of convertions between charsets (when we don’t know the source charset and what is the convenient destination charset) this is an example : = array( «UTF-8» , «ASCII» , «Windows-1252» , «ISO-8859-15» , «ISO-8859-1» , «ISO-8859-6» , «CP1256» );
$chain = «» ;
foreach ( $tab as $i )

> echo $chain ;
?> then after displaying, you use the $i$j that shows good displaying.
NB: you can add other charsets to $tab to test other cases.

If you are getting question-marks in your iconv output when transliterating, be sure to ‘setlocale’ to something your system supports. Some PHP CMS’s will default setlocale to ‘C’, this can be a problem. use the «locale» command to find out a list.. ( LC_CTYPE , ‘en_AU.utf8’ );
$str = iconv ( ‘UTF-8’ , ‘ASCII//TRANSLIT’ , «Côte d’Ivoire» );
?> Like many other people, I have encountered massive problems when using iconv() to convert between encodings (from UTF-8 to ISO-8859-15 in my case), especially on large strings. The main problem here is that when your string contains illegal UTF-8 characters, there is no really straight forward way to handle those. iconv() simply (and silently!) terminates the string when encountering the problematic characters (also if using //IGNORE), returning a clipped string. The = html_entity_decode ( htmlentities ( $oldstring , ENT_QUOTES , ‘UTF-8’ ), ENT_QUOTES , ‘ISO-8859-15’ );

Читайте также:  Часы кожа питона ремешок

?> workaround suggested here and elsewhere will also break when encountering illegal characters, at least dropping a useful note («htmlentities(): Invalid multibyte sequence in argument in. «) I have found a lot of hints, suggestions and alternative methods (it’s scary and in my opinion no good sign how many ways PHP natively provides to convert the encoding of strings), but none of them really worked, except for this one: = mb_convert_encoding ( $oldstring , ‘ISO-8859-15’ , ‘UTF-8’ ); For those who have troubles in displaying UCS-2 data on browser, here’s a simple function that convert ucs2 to html unicode entities : function ucs2html ( $str )
?> There may be situations when a new version of a web site, all in UTF-8, has to display some old data remaining in the database with ISO-8859-1 accents. The problem is iconv(«ISO-8859-1», «UTF-8», $string) should not be applied if $string is already UTF-8 encoded.

I use this function that does’nt need any extension : function convert_utf8( $string ) else
> I have not tested it extensively, hope it may help. Here is how to convert UCS-2 numbers to UTF-8 numbers in hex: function ucs2toutf8 ( $str )

else

$utf8 .= $byte1 . $byte2 ;
>
return $utf8 ;
> echo strtoupper ( ucs2toutf8 ( «06450631062D0020» ));

?> Input:
06450631062D
Output:
D985D8B1D8AD I have used iconv to convert from cp1251 into UTF-8. I spent a day to investigate why a string with Russian capital ‘Р’ (sounds similar to ‘r’) at the end cannot be inserted into a database. The problem is not in iconv. But ‘Р’ in cp1251 is chr(208) and ‘Р’ in UTF-8 is chr(208).chr(106). chr(106) is one of the space symbol which match ‘\s’ in regex. So, it can be taken by a greedy ‘+’ or ‘*’ operator. In that case, you loose ‘Р’ in your string. For example, ‘ГР ‘ (Russian, UTF-8). Function preg_match. Regex is ‘(.+?)[\s]*’. Then ‘(.+?)’ matches ‘Г’.chr(208) and ‘[\s]*’ matches chr(106).’ ‘. Although, it is not a bug of iconv, but it looks like it very much. That’s why I put this comment here. Didn’t know its a feature or not but its works for me (PHP 5.0.4)

test it to convert from windows-1251 (stored in DB) to UTF-8 (which i use for web pages).
BTW i convert each array i fetch from DB with array_walk_recursive. In my case, I had to change:
( LC_CTYPE , ‘cs_CZ’ );
?>
to
( LC_CTYPE , ‘cs_CZ.UTF-8’ );
?>
Otherwise it returns question marks. When I asked my linux for locale (by locale command) it returns «cs_CZ.UTF-8», so there is maybe correlation between it. iconv (GNU libc) 2.6.1
glibc 2.3.6 I just found out today that the Windows and *NIX versions of PHP use different iconv libraries and are not very consistent with each other. Here is a repost of my earlier code that now works on more systems. It converts as much as possible and replaces the rest with question marks: if (! function_exists ( ‘utf8_to_ascii’ ))
>
else
elseif ( is_array ( $text ) && count ( $text ) == 1 && is_string ( $text [ 0 ]))
elseif ( preg_match ( ‘/\w/’ , $text ))
>
else
return $text ;
>
>
>

Here is an example how to convert windows-1251 (windows) or cp1251(Linux/Unix) encoded string to UTF-8 encoding. function cp1251_utf8 ( $sInput )
= 192 and $c 239 ) $t .= $c208 . chr ( $c — 48 );
elseif ( $c > 239 ) $t .= $c209 . chr ( $c — 112 );
elseif ( $c == 184 ) $t .= $c209 . $c209 ;
elseif ( $c == 168 ) $t .= $c208 . $c129 ;
else $t .= $s [ $i ];
>
return $t ;
>
else

> function utf8_to_cp1251 ( $s )
> 2 )& 5 ;
$new_i = $new_c1 * 256 + $new_c2 ;
if ( $new_i == 1025 )
else else
>
$out .= chr ( $out_i );
$byte2 = false ;
>
if (( $i >> 5 )== 6 )

>
return $out ;
>
else

>
?> If you need convert string from Windows-1251 to 866. Some characters of 1251 haven’t representation on DOS 866. For example, long dash — chr(150) will be converted to 0, after that iconv finish his work and other charactes will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190). //$text — input text in windows-1251
//$cout — output text in 866 (cp866, dos ru ascii)

Одминский блог

Смена кодировки сайта из CP1251 на UTF-8

Перевозил тут пачку сайтов с LAMP на LNAMP, где фронтэндом выступает NGINX. И все бы ничего, если бы не пачка статических сателлитов в кодировке Windows-1251 (cp1251). Как тут прикололся девака – при анализе сайта, надо сначала чекать кодировку и в случае обнаружения кодировки сайта cp1251 – проверку возраста можно не осуществлять. Но, тем не менее, в инетах до сих пор встречаются такие мастадонты, которые клепают сайты в кодировке CP1251. Под апачем, при добавлении сайта в ISP Panel это даже не заметишь, а вот при попытке добавить этот же сайт в Vesta CP, получаешь гемор на задницу с крикозябрами. Поэтому надо редактировать конфиг Nginx, предварительно прикрутив туда виндовую кодировку. Но, насколько я помню, у меня этот танец с бубнами не задался и в тот раз, я просто повесил саты на LAMP. Так что оставалось либо плясать с бубнами вокруг прикручивания виндовой кодировки к NGINX, либо перекодивать файлы в родную для нжинкса UTF-8. Сделать это можно средствами текстового редактора Notepad++ путем перевода кодировки документа и последующего сохранения; либо же в самом линухе. Как я выше заметил, саты статические, то есть на файлах, без использования базы данных. Поэтому перекодировать надо было именно файлы. С базой данных все происходило бы несколько иначе.

Перекодировка файла из CP1251 в UTF-8 производится в консоли через команду iconv
# iconv -f cp1251 -t utf8 FILE-CP1251 -o FILE-UTF8
либо же можно переписать файл в самого себя
# iconv -f cp1251 -t utf8 file.txt -o file.txt Но поскольку мне надо было перекодировать большое число файлов php, содержащихся в разных папках, то мне пришлось составить небольшое предложение:
# find /path-to-files/ -type f -name \*php -exec iconv -f cp1251 -t utf-8 ‘<>‘ -o ‘<>‘ \; Конвертит все в лет. Для конвертации кодировок есть еще утилита enconv, входящая в состав пакета enca – вот он как раз конвертит сам в себя по умолчанию, перезаписывая файл выходной кодировкой:
# enconv -c file.txt но, к сожалению, я его не смог подружить с русским языком, т.к даже при указании языка через ключик -L russian скрипт матерился на ошибки. Но с другой стороны, все нормально решилось и через iconv Источник

Источник

Смотрите также

This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.

function cp1251_to_utf8 ( $s )
<
if (( mb_detect_encoding ( $s , ‘UTF-8,CP1251’ )) == «WINDOWS-1251» )
<
$c209 = chr ( 209 ); $c208 = chr ( 208 ); $c129 = chr ( 129 );
for( $i = 0 ; $i < strlen ( $s ); $i ++)
<
$c = ord ( $s [ $i ]);
if ( $c >= 192 and $c elseif ( $c > 239 ) $t .= $c209 . chr ( $c — 112 );
elseif ( $c == 184 ) $t .= $c209 . $c209 ;
elseif ( $c == 168 ) $t .= $c208 . $c129 ;
else $t .= $s [ $i ];
>
return $t ;
>
else
<
return $s ;
>
>

function utf8_to_cp1251 ( $s )
<
if (( mb_detect_encoding ( $s , ‘UTF-8,CP1251’ )) == «UTF-8» )
<
for ( $c = 0 ; $c < strlen ( $s ); $c ++)
<
$i = ord ( $s [ $c ]);
if ( $i if ( $byte2 )
<
$new_c2 =( $c1 & 3 )* 64 +( $i & 63 );
$new_c1 =( $c1 >> 2 )& 5 ;
$new_i = $new_c1 * 256 + $new_c2 ;
if ( $new_i == 1025 )
<
$out_i = 168 ;
> else <
if ( $new_i == 1105 )
<
$out_i = 184 ;
> else <
$out_i = $new_i — 848 ;
>
>
$out .= chr ( $out_i );
$byte2 = false ;
>
if (( $i >> 5 )== 6 )
<
$c1 = $i ;
$byte2 = true ;
>
>
return $out ;
>
else
<
return $s ;
>
>
?>

If you need convert string from Windows-1251 to 866. Some characters of 1251 haven’t representation on DOS 866. For example, long dash — chr(150) will be converted to 0, after that iconv finish his work and other charactes will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).

//$text — input text in windows-1251
//$cout — output text in 866 (cp866, dos ru ascii)

Источник

Оцените статью