Php convert windows 1251 to utf

Конвертация кодировок utf-8 и win-1251 в PHP через iconv

Обычно php страница или сайт имеет одну базовую кодировку. Я работаю только с UTF-8, но бывают случаи, когда приходится использовать какой-нибудь php файл с кодировкой win-1251, а передаваемые в него значения идут в кодировке UTF-8. В этом случае после исполнения скрипта появляются кракозябры.

Таких ситуаций может быть множество, например, при использовании функции отправки сообщений mail(), работе с PDF обработкой или даже при различных действиях с БД. В идеале нужно обязательно избавляться от таких хвостов и не допускать в коде функции конвертации, но если это просто невозможно, то на помощь вам придет функция iconv.

Синтаксис функции: $string= iconv(‘начальная кодировка’, ‘конечная кодировка’, $string);

Здесь $string — строка, кодировку которой мы изменяем

Из этого выходит, что для того, чтобы преобразовать строку из кодировки utf-8 в win-1251 нужно писать следующее: $string= iconv(‘utf-8’, ‘win-1251’, $string);

Из win-1251 в utf-8: $string= iconv(‘win-1251’, ‘utf-8’, $string);

На заметку, помните, что кодировку в php странице можно указывать за счет установки header-а документа. Например, если ваша страница в UTF-8 без BOM, то в самом начале документа ставьте: . Если же windows 1251, то сам документ должен быть в ANSI, а в первой строке можете поставить: . Иногда эти манипуляции помогают с письмами, которые приходят в кракозябрах из-за неверной кодировки.

Перекодировка строки cp1251 в utf8

Здравствуйте! Помогите советом, плз. Нужно получить заголовок страницы, и, если кодировка страницы cp1251, перекодировать ее в utf8. Пробую так:

Перекодировка строки из UTF8 в cp1251
Доброго времени суток. Почему не получается из UTF8 преобразовать в cp1251? std::string.

Перекодировка строки из cp1251 в UTF8
Доброго времени суток. У меня есть строка в cp1251, но мне нужно вывести в utf8. Как это лучше.

разберитесь как правильно получить кодировку, которую использует страница

кастати, нашел кажется почти то, что вам нужно (адаптируете под свою задачу) вот тут

определение кодировки из полученного текста неблагодарное дело ибо оно опирается на статистический вес буквы
гораздо удобнее из заголовка взять charset и, опираясь на него, выяснить что за кодировка

обратите снимание что если в php.ini установлена кодировка windows-1251 или другая, то даже если вы заголовок поставите urf-8, кодировка будет та, которую установит php-машина. потому если случаются такие каверзы используйте set_ini(. ..)

у меня такая проблема была

так да, берет. я же не говорил что не берет

Добавлено через 4 минуты
во, нашел заметку, о которой я говорил: http://habrahabr.ru/blogs/php/107945/
особенно порадовал код:

Тематические курсы и обучение профессиям онлайн
Профессия‌ ‌PHP-разработчик (Skillbox)‌
Fullstack-разработчик на PHP (Skillbox)‌
Веб-разработчик с нуля (Нетология)
Профессия веб-разработчик (Skillbox)

В cp1251 русские буквы А-Яа-я (без буквы Ёё) занимают диапазон ASCII кодов 192-255 (0xC0-0xFF), а в юникоде — 1040-1104 (0x0410-0x044F). Разница как раз 848.

Буква Ёё отдыхает, я так понимаю. Кустарный способ.

Читайте также:  Pantone colorvision profilerplus windows 10

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

из utf8 в cp1251
Всем привет ! Собственно сразу вопрос — как троку перекодировать из utf8 в cp1251 и обратно ? .

преобразования utf8 cp1251
Какими функциями лучше всего воспользоваться для преобразований utf8 в cp1251 и обратно ?

Перевод из cp1251 в utf8
Как перевести программно на C# это: %CA%D0%C8% в читабельный текст?

Перекодировка DBF файла из cp1251 в UTF-8
Есть dbf файл (база БИК), он сохранен в cp1251, как данные из него перекодировать в UTF-8? сам.

Конвертер из UTF8 — cp1251 и наоборот
Доброго времени суток. Я понимаю, что данная тема уже поднималась на форуме, но я нашел код на c#.

Из кода символа Cp1251 получить UTF8 символ
Мучаюсь с быстрым выводом текста на канву (пишу текстовый редактор) пробовал вывод теста.

Функции iconv

Содержание

User Contributed Notes 2 notes

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 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
<
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 127 ) $out .= $s [ $c ];
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)

for($i=0;$i =192&&$ord =240&&$ord =128&&$ord

convert_cyr_string

(PHP 4, PHP 5, PHP 7)

convert_cyr_string — Преобразует строку из одной кириллической кодировки в другую

Эта функция объявлена УСТАРЕВШЕЙ, начиная с PHP 7.3.0 и была УДАЛЕНА в версии PHP 8.0.0. Использовать эту функцию крайне не рекомендуется.

Описание

Преобразует строку из одной кириллической кодировки в другую.

Список параметров

Исходная кириллическая кодировка, один символ.

Целевая кириллическая кодировка, один символ.

Поддерживаются следующие символы:

  • k — koi8-r
  • w — windows-1251
  • i — iso8859-5
  • a — x-cp866
  • d — x-cp866
  • m — x-mac-cyrillic

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

Возвращает преобразованную строку.

Читайте также:  Windows 10 pro vpn server

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

  • mb_convert_encoding() — Преобразует кодировку символов
  • iconv() — Преобразование строки в требуемую кодировку

User Contributed Notes 16 notes

To: mihailsbo at lycos dot ru
Transliteration could be done easier:

Only this code works OK for me, for translating win-1251 to utf-8 for macedonian letters!

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) <
$encode = «»;

if(ord($xchr) == 188) <
$xchr = «ј»;
>
if(ord($xchr) == 131) <
$xchr = «ѓ»;
>
if(ord($xchr) == 190) <
$xchr = «ѕ»;
>
if(ord($xchr) == 154) <
$xchr = «љ»;
>
if(ord($xchr) == 156) <
$xchr = «њ»;
>
if(ord($xchr) == 159) <
$xchr = «џ»;
>
if(ord($xchr) == 157) <
$xchr = «ќ»;
>
$encode=$encode . $xchr;
>
return $encode;
>

A better function to convert cp1251 string to utf8.
Works with russian and ukrainian text.

function unicod($str) <
$conv=array();
for($x=128;$x

Sorry for my previous post. NOT array_reverce, array_flip is actual function. Correct function:

function Encode($str,$type=u)
<
$conv=array();
for($x=192;$x

Check this code — exelent to convert win-1251 to UTF-8
just one fix.
if ($c==184) < $t.=chr(209).chr(145); continue; >;

Anything more it is not necessary.
It is grateful to threed [at] koralsoft.com
28-Jul-2003 03:37
i tried all functions here to convert from cp1251 to unicode, but they don’t work. i think that this work :

i tried all functions here to convert from cp1251 to unicode, but they don’t work. i think that this work :

//I’ve also built the same way for hebrew to utf converting

for($i=0, $m=strlen($s); $i =224 )

//Simple unicoder and decoder for hebrew and russian:

function unicode_hebrew($str) <
for ($ii=0;$ii 223) <
$xchr=ord($xchr)+1264;
$xchr=»&#» . $xchr . «;»;
>
$encode=$encode . $xchr;

function unicode_russian($str) <
for ($ii=0;$ii 191) <
$xchr=ord($xchr)+848;
$xchr=»&#» . $xchr . «;»;
>
$encode=$encode . $xchr;

function decode_unicoded_hebrew($str) <
$decode=»»;

foreach ($ar as $value ) <

$in1=strpos($value,»;»); //end of code

if ($code>=1456 and $code 0)

if ($code>=1040 and $code

🙂 what about NUMBER.

function Utf8Win($str,$type=»w»)
<
static $conv=»;
if (!is_array($conv))
<
$conv = array();
for($x=128;$x

\n»;
code should be like this:

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) <
$encode = «»;

if(ord($xchr) == 188) <
$xchr = «ј»;
>
if(ord($xchr) == 131) <
$xchr = «ѓ»;
>
if(ord($xchr) == 190) <
$xchr = «ѕ»;
>
if(ord($xchr) == 154) <
$xchr = «љ»;
>
if(ord($xchr) == 156) <
$xchr = «њ»;
>
if(ord($xchr) == 159) <
$xchr = «џ»;
>
if(ord($xchr) == 157) <
$xchr = «ќ»;
>
$encode=$encode . $xchr;
>
return $encode;
>

previous bit of code (grmaxim’s win_to_utf8 function) didn’t work for me, so I wrote my own func to convert from win1251 to utf8:

function win2utf ( $s ) <
for( $i = 0 , $m = strlen ( $s ); $i $m ; $i ++) <
$c = ord ( $s [ $i ]);
if ( $c > 127 ) // convert only special chars
if ( $c == 184 ) $t .= chr ( 209 ). chr ( 209 ); // small io
elseif ( $c == 168 ) $t .= chr ( 208 ). chr ( 129 ); // capital io
else $t .=( $c > 239 ? chr ( 209 ): chr ( 208 )). chr ( $c — 48 );
else $t .= $s [ $i ];
>
return $t ;
>
?>

Hope this helps

Читайте также:  Tune windows tcp ip

Praising other people for their efforts to write a convenient UTF8 to Win-1251 functions may I mention that, since str_replace allows arrays as parameters, the function may be rewritten in a slightly efficient way (moreover, the array generated may be stored for performance improvement):

function Encode ( $str , $type )
<
// $type:
// ‘w’ — encodes from UTF to win
// ‘u’ — encodes from win to UTF

static $conv = » ;
if (! is_array ( $conv ))
<
$conv =array ();
for ( $x = 128 ; $x 143 ; $x ++ )
<
$conv [ ‘utf’ ][]= chr ( 209 ). chr ( $x );
$conv [ ‘win’ ][]= chr ( $x + 112 );
>

for ( $x = 144 ; $x 191 ; $x ++ )
<
$conv [ ‘utf’ ][]= chr ( 208 ). chr ( $x );
$conv [ ‘win’ ][]= chr ( $x + 48 );
>

$conv [ ‘utf’ ][]= chr ( 208 ). chr ( 129 );
$conv [ ‘win’ ][]= chr ( 168 );
$conv [ ‘utf’ ][]= chr ( 209 ). chr ( 145 );
$conv [ ‘win’ ][]= chr ( 184 );
>
if ( $type == ‘w’ )
return str_replace ( $conv [ ‘utf’ ], $conv [ ‘win’ ], $str );
elseif ( $type == ‘u’ )
return str_replace ( $conv [ ‘win’ ], $conv [ ‘utf’ ], $str );
else
return $str ;
>
?>

Unfortunately input data must be a string only. But it is may be changed! 😉

To convert multi-dimensional array I use this recursive function:

function convert_cyr_array ( $array , $from , $to ) <
foreach( $array as $key => $value ) <
if( is_array ( $value )) <
$result [ $key ] = convert_cyr_array ( $value , $from , $to );
continue;
>
$result [ $key ] = convert_cyr_string ( $value , $from , $to );
>
return $result ;
>
?>

An example:

[ 0 ] = «сВМПЛП» ;
$array [ 1 ] = «зТХЫБ» ;
$array [ 2 ] = array( «пЗХТЕГ» , «рПНЙДПТ» );
$array [ 3 ] = array(
array( «бРЕМШУЙО» , «нБОДБТЙО» ),
array( «бВТЙЛПУ» , «рЕТУЙЛ» )
);

$result = convert_cyr_array ( $array , «k» , «w» );
/* Returns:

Convert from mysql cp1251_general_ci collation (Windows-1251) into UTF-8 php

I have a mysql varchar(50) row in cp1251_general_ci collation. After mysql_fetch_row in php i got a $string. Then i do the following:

Why the second time the string is not UTF-8?

But again the out charset is Windows-1251.

And in the final result i got broken encoding in my filename which consists of $string variable.

How can i convert from mysql cp1251_general_ci collation (Windows-1251) into UTF-8?

creates a file . /tmp/. log (in linux)

1 Answer 1

Found the reason of this strange situation!

In short words: if you see a proper encoded UTF-8 string on a server (in terminal) in unreadable symbols — check the server locale. And if you see a strange behavior of the mb_detect_encoding() method, don’t forget that — mb_detect_encoding doesn’t give you a precise encoding determination of a string.

The reason of not correct encoding in filename: . /tmp/. log file is the locale on the server! Here is the locale command result on the server where the file is located:

For correct displaying UFT-8 symbols in file names on the server the server locale must be utf-8 too.

And about all the converting in the question. Both methods:

works fine in this case.

The only question is why the second echo of

And the answer is — mb_detect_encoding doesn’t give you a precise encoding determination of a string

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