Php output in utf 8

mb_internal_encoding

encoding — это имя кодировки, в которую будут преобразовываться входные данные HTTP-запроса, из которой будет конвертироваться HTTP-вывод, а также это кодировка по умолчанию для всех функций, работающих со строками, определёнными в модуле mbstring. Обратите внимание, что внутренняя кодировка полностью отличается от кодировки для многобайтовых регулярных выражений.

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

Если аргумент encoding задан, то Возвращает true в случае успешного выполнения или false в случае возникновения ошибки. В этом случае не меняется кодировка символов для многобайтных регулярных выражений. Если аргумент encoding опущен, будет возвращено имя текущей внутренней кодировки.

Ошибки

Начиная с PHP 8.0.0, выбрасывается исключение ValueError , если значение параметра encoding является недопустимой кодировкой. До PHP 8.0.0 вместо этого выдавалась ошибка уровня E_WARNING .

Список изменений

Версия Описание
8.0.0 Теперь параметр encoding может принимать значение null .
8.0.0 Теперь выбрасывается исключение ValueError , если значение параметра encoding является недопустимой кодировкой. Ранее вместо этого выдавалась ошибка уровня E_WARNING .

Примеры

Пример #1 Пример использования mb_internal_encoding()

/* Установка внутренней кодировки в UTF-8 */
mb_internal_encoding ( «UTF-8» );

/* Вывод на экран текущей внутренней кодировки */
echo mb_internal_encoding ();
?>

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

  • mb_http_input() — Определение кодировки символов входных данных HTTP-запроса
  • mb_http_output() — Установка/получение кодировки символов вывода HTTP
  • mb_detect_order() — Установка/получение списка кодировок для механизмов определения кодировки
  • mb_regex_encoding() — Устанавливает/получает текущую кодировку для многобайтового регулярного выражения
Читайте также:  Формы

User Contributed Notes 7 notes

Especially when writing PHP scripts for use on different servers, it is a very good idea to explicitly set the internal encoding somewhere on top of every document served, e.g.

This, in combination with mysql-statement «SET NAMES ‘utf8′», will save a lot of debugging trouble.

Also, use the multi-byte string functions instead of the ones you may be used to, e.g. mb_strlen() instead of strlen(), etc.

header ( ‘Content-Type: text/html; charset=UTF-8’ );

mb_internal_encoding ( ‘UTF-8’ );
mb_http_output ( ‘UTF-8’ );
mb_http_input ( ‘UTF-8’ );
mb_regex_encoding ( ‘UTF-8’ );

Be aware that the strings in your source files must match the encoding you specify by mb_internal_encoding. It appears the Parser loads raw bytes from the file and refers to its internal encoding to determine their actual encoding.

To demonstrate, the following outputs as espected when the /source/ file is Latin-1 encoded:

mb_internal_encoding ( «iso-8859-1» );
mb_http_output ( «UTF-8» );
ob_start ( «mb_output_handler» );

Now, a typical use of mb_internal_encoding is shown as follows. Make the change to «utf-8» but leave the /source/ file encoding unchanged:

mb_internal_encoding ( «UTF-8» );
mb_http_output ( «UTF-8» );
ob_start ( «mb_output_handler» );

The output will just show the
tag and no text.

Save the file as UTF-8 encoding and then the results will be as expected.

Источник

utf8_encode

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

Описание

Функция преобразует строку string из кодировки ISO-8859-1 в кодировку UTF-8 .

Замечание:

Функция не пытается угадать текущую кодировку предоставленной строки, а предполагает, что она закодирована в ISO-8859-1 (также известная как «Latin 1») и преобразует её в UTF-8. Поскольку каждая последовательность байтов является корректной строкой ISO-8859-1, это никогда не приводит к ошибке, но не приведёт к получению полезной строки, если предполагалась другая кодировка.

Многие веб-страницы, отмеченные как использующие кодировку ISO-8859-1 , на самом деле используют схожую кодировку Windows-1252 , и веб-браузеры интерпретируют страницы ISO-8859-1 как Windows-1252 . Однако Windows-1252 содержит дополнительные печатные символы, такие как знак Евро ( € ) и фигурные кавычки ( “ ” ) вместо управляющих кодов ISO-8859-1 . Эта функция не конвертирует такие символы Windows-1252 корректно. Используйте другую функцию, если нужна конвертация из Windows-1252 .

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

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

Возвращает строку string , преобразованную в кодировку в UTF-8.

Список изменений

Версия Описание
8.2.0 This function has been deprecated.
7.2.0 Функция была перенесена из модуля XML в ядро PHP. В предыдущих версиях она была доступна только при установленном модуле XML.

Примеры

Пример #1 Простой пример

// Преобразование строки ‘Zoë’ из ISO 8859-1 в UTF-8
$iso8859_1_string = «\x5A\x6F\xEB» ;
$utf8_string = utf8_encode ( $iso8859_1_string );
echo bin2hex ( $utf8_string ), «\n» ;
?>

Результат выполнения данного примера:

Примечания

Замечание: Устаревание и альтернативы

Функция устарела, начиная с PHP 8.2.0 и будет удалена в будущей версии. Существующие варианты использования должны быть проверены и заменены подходящими альтернативами.

Аналогичной функциональности можно достичь с помощью функции mb_convert_encoding() , которая поддерживает ISO-8859-1 и многие другие кодировки символов.

$iso8859_1_string = «\xEB» ; // ‘ë’ (e с диерезисом) в UTF-8
$utf8_string = mb_convert_encoding ( $iso8859_1_string , ‘UTF-8’ , ‘ISO-8859-1’ );
echo bin2hex ( $utf8_string ), «\n» ;

$iso8859_7_string = «\xEB» ; // та же строка в ISO-8859-7 представляет собой ‘λ’ (греческая строчная лямбда)
$utf8_string = mb_convert_encoding ( $iso8859_7_string , ‘UTF-8’ , ‘ISO-8859-7’ );
echo bin2hex ( $utf8_string ), «\n» ;

$windows_1252_string = «\x80» ; // ‘€’ (Знак евро) в Windows-1252, но не в ISO-8859-1
$utf8_string = mb_convert_encoding ( $windows_1252_string , ‘UTF-8’ , ‘Windows-1252’ );
echo bin2hex ( $utf8_string ), «\n» ;
?>

Результат выполнения данного примера:

Другие опции, которые могут быть доступны в зависимости от установленных модулей: UConverter::transcode() и iconv() .

Все следующие варианты дают один и тот же результат:

$iso8859_1_string = «\x5A\x6F\xEB» ; // ‘Zoë’ в ISO-8859-1

$utf8_string = utf8_encode ( $iso8859_1_string );
echo bin2hex ( $utf8_string ), «\n» ;

$utf8_string = mb_convert_encoding ( $iso8859_1_string , ‘UTF-8’ , ‘ISO-8859-1’ );
echo bin2hex ( $utf8_string ), «\n» ;

$utf8_string = UConverter :: transcode ( $iso8859_1_string , ‘UTF8’ , ‘ISO-8859-1’ );
echo bin2hex ( $utf8_string ), «\n» ;

$utf8_string = iconv ( ‘ISO-8859-1’ , ‘UTF-8’ , $iso8859_1_string );
echo bin2hex ( $utf8_string ), «\n» ;
?>

Результат выполнения данного примера:

5a6fc3ab 5a6fc3ab 5a6fc3ab 5a6fc3ab

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

  • utf8_decode() — Преобразует строку из UTF-8 в ISO-8859-1, заменяя недопустимые или непредставимые символы
  • mb_convert_encoding() — Преобразует строку из одной кодировки символов в другую
  • UConverter::transcode() — Преобразует строку из одной кодировки символов в другую
  • iconv() — Преобразует строку из одной кодировки символов в другую

User Contributed Notes 24 notes

Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8. A more appropriate name for it would be «iso88591_to_utf8». If your text is not encoded in ISO-8859-1, you do not need this function. If your text is already in UTF-8, you do not need this function. In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

If you need to convert text from any encoding to any other encoding, look at iconv() instead.

Here’s some code that addresses the issue that Steven describes in the previous comment;

/* This structure encodes the difference between ISO-8859-1 and Windows-1252,
as a map from the UTF-8 encoding of some ISO-8859-1 control characters to
the UTF-8 encoding of the non-control characters that Windows-1252 places
at the equivalent code points. */

$cp1252_map = array(
«\xc2\x80» => «\xe2\x82\xac» , /* EURO SIGN */
«\xc2\x82» => «\xe2\x80\x9a» , /* SINGLE LOW-9 QUOTATION MARK */
«\xc2\x83» => «\xc6\x92» , /* LATIN SMALL LETTER F WITH HOOK */
«\xc2\x84» => «\xe2\x80\x9e» , /* DOUBLE LOW-9 QUOTATION MARK */
«\xc2\x85» => «\xe2\x80\xa6» , /* HORIZONTAL ELLIPSIS */
«\xc2\x86» => «\xe2\x80\xa0» , /* DAGGER */
«\xc2\x87» => «\xe2\x80\xa1» , /* DOUBLE DAGGER */
«\xc2\x88» => «\xcb\x86» , /* MODIFIER LETTER CIRCUMFLEX ACCENT */
«\xc2\x89» => «\xe2\x80\xb0» , /* PER MILLE SIGN */
«\xc2\x8a» => «\xc5\xa0» , /* LATIN CAPITAL LETTER S WITH CARON */
«\xc2\x8b» => «\xe2\x80\xb9» , /* SINGLE LEFT-POINTING ANGLE QUOTATION */
«\xc2\x8c» => «\xc5\x92» , /* LATIN CAPITAL LIGATURE OE */
«\xc2\x8e» => «\xc5\xbd» , /* LATIN CAPITAL LETTER Z WITH CARON */
«\xc2\x91» => «\xe2\x80\x98» , /* LEFT SINGLE QUOTATION MARK */
«\xc2\x92» => «\xe2\x80\x99» , /* RIGHT SINGLE QUOTATION MARK */
«\xc2\x93» => «\xe2\x80\x9c» , /* LEFT DOUBLE QUOTATION MARK */
«\xc2\x94» => «\xe2\x80\x9d» , /* RIGHT DOUBLE QUOTATION MARK */
«\xc2\x95» => «\xe2\x80\xa2» , /* BULLET */
«\xc2\x96» => «\xe2\x80\x93» , /* EN DASH */
«\xc2\x97» => «\xe2\x80\x94» , /* EM DASH */

«\xc2\x98» => «\xcb\x9c» , /* SMALL TILDE */
«\xc2\x99» => «\xe2\x84\xa2» , /* TRADE MARK SIGN */
«\xc2\x9a» => «\xc5\xa1» , /* LATIN SMALL LETTER S WITH CARON */
«\xc2\x9b» => «\xe2\x80\xba» , /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
«\xc2\x9c» => «\xc5\x93» , /* LATIN SMALL LIGATURE OE */
«\xc2\x9e» => «\xc5\xbe» , /* LATIN SMALL LETTER Z WITH CARON */
«\xc2\x9f» => «\xc5\xb8» /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

function cp1252_to_utf8 ( $str ) global $cp1252_map ;
return strtr ( utf8_encode ( $str ), $cp1252_map );
>

For reference, it may be insightful to point out that:
utf8_encode($s)
is actually identical to:
recode_string(‘latin1..utf8’, $s)
and:
iconv(‘iso-8859-1’, ‘utf-8’, $s)
That is, utf8_encode is a specialized case of character set conversions.

If your string to be converted to utf-8 is something other than iso-8859-1 (such as iso-8859-2 (Polish/Croatian)), you should use recode_string() or iconv() instead rather than trying to devise complex str_replace statements.

If you haven’t guessed already: If the UTF-8 character has no representation in the ISO-8859-1 codepage, a ? will be returned. You might want to wrap a function around this to make sure you aren’t saving a bunch of . into your database.

If you need a function which converts a string array into a utf8 encoded string array then this function might be useful for you:

Источник

PHP UTF-8 Conversion

PHP UTF-8 Conversion

  1. Use utf8_encode() and utf8_decode() to Encode and Decode Strings in PHP
  2. Use iconv() to Convert a String to UTF-8

The UTF-8 is a way to encode Unicode characters, each character in between one to four bytes.

It is used to handle the special character or characters from languages other than English.

PHP has different ways to convert text into UTF-8 .

Use utf8_encode() and utf8_decode() to Encode and Decode Strings in PHP

Both utf8_encode() and utf8_decode() are built-in functions in PHP.

It is used to encode and decode ISO-8859-1 , and other types of strings to UTF-8 , both of these function takes a string as a parameter.

php $demo="\xE0\xE9\xED"; //ISO-8859-1 String àéí  echo "UTF-8 Encoded String: "; echo utf8_encode($demo) ."
"
;
echo "UTF-8 Decoded String: "; echo utf8_decode(utf8_encode($demo)) ."
"
;
echo "UTF-8 Encoded String from the decoded: "; echo utf8_encode(utf8_decode(utf8_encode($demo))) ."
"
;
?>

The code above encodes an ISO-8859-1 string to UTF and then decodes the output again. The input string you see is with ISO-8859-1 encoding.

UTF-8 Encoded String: àéí UTF-8 Decoded String: ��� UTF-8 Encoded String from the decoded: àéí 

The utf8_decode() converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1 .

When reading an ISO-8859-1 encoded text as UTF-8 , you will often see that question mark.

Use iconv() to Convert a String to UTF-8

iconv() is another built-in PHP function used to convert string from one Unicode.

It takes three parameters, one is the string’s Unicode, the second is the Unicode you want to convert, and the third is the string itself.

php $demo="\xE0\xE9\xED"; //ISO-8859-1 String àéí  echo "The UTF-8 String is: "; echo iconv("ISO-8859-1", "UTF-8", $demo)."
"
;
//mb_detect_encoding() is a function used to detect encoding of the given text. echo "The UTF-8 String with auto detection is: "; echo iconv(mb_detect_encoding($demo, mb_detect_order(), true), "UTF-8", $demo); ?>

The code above takes three parameters and converts the text to UTF-8 .

The UTF-8 String is: àéí The UTF-8 String with auto detection is: àéí 

PHP also offers other functions like recode_string() or mb_convert_encoding() , which works similarly to iconv ; they convert a string to the requested Unicode.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Related Article — PHP Encode

Источник

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