Charset in php file

Перекодировка текста UTF-8 и WINDOWS-1251

Проблема кодировок часто возникает при написании парсеров, чтении данных из xml и CSV файлов. Ниже представлены способы эту проблему решить.

windows-1251 в UTF-8

$text = iconv('windows-1251//IGNORE', 'UTF-8//IGNORE', $text); echo $text;
$text = mb_convert_encoding($text, 'UTF-8', 'windows-1251'); echo $text;

UTF-8 в windows-1251

$text = iconv('utf-8//IGNORE', 'windows-1251//IGNORE', $text); echo $text;
$text = mb_convert_encoding($text, 'windows-1251', 'utf-8'); echo $text;

Когда ни что не помогает

$text = iconv('utf-8//IGNORE', 'cp1252//IGNORE', $text); $text = iconv('cp1251//IGNORE', 'utf-8//IGNORE', $text); echo $text;

Иногда доходит до бреда, но работает:

$text = iconv('utf-8//IGNORE', 'windows-1251//IGNORE', $text); $text = iconv('windows-1251//IGNORE', 'utf-8//IGNORE', $text); echo $text;

File_get_contents / CURL

Бывают случаи когда file_get_contents() или CURL возвращают иероглифы (Алмазные борÑ) – причина тут не в кодировке, а в отсутствии BOM-метки.

$text = file_get_contents('https://example.com'); $text = "\xEF\xBB\xBF" . $text; echo $text;

Ещё бывают случаи, когда file_get_contents() возвращает текст в виде:

Это сжатый текст в GZIP, т.к. функция не отправляет правильные заголовки. Решение проблемы через CURL:

function getcontents($url) < $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_ENCODING, 'gzip'); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $output = curl_exec($ch); curl_close($ch); return $output; >echo getcontents('https://example.com');

Источник

Setting charset in php

So be aware of possible HTML not parsing when using text type . Solution 1: Solution 2: Also note that setting a header to will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML.

Setting charset in php

How to send data in php with ANSI charset ? As defaults is UTF-8

header('Content-Type: text/plain; charset=ansi'); 

If by ANSI you mean «Windows Western», you should use charset=windows-1252 rather than us-ascii.

«text/plain; charset=us-ascii» , see RFC http://www.w3.org/Protocols/rfc1341/7_1_Text.html

PHP mysqli_set_charset() Function, The mysqli_set_charset () function is used to specify the default character set to send data to the database server from mysqli client. Syntax mysqli_set_charset ($con, charset) Parameters Return Values The mysqli_set_charset () function returns true if incase of success and false if failed. PHP Version

How to set «set_charset(‘utf8’);» for the entire class

Hi I know how to set «set_charset(‘utf8’);» with style:

$db = new mysqli('127.0.0.1','root','pass','data') or die ('error with connection'); $db->set_charset('utf8'); 

But now I want to do this with classes like:

class Core < protected $db, $result; private $rows; public function __construct()< $this->db = new mysqli('127.0.0.1','root','pass','data'); > public function query ($sql)< $this->result = $this->db->query($sql); > public function rows()< for($x =1; $xdb->affected_rows; $x++)< $this->rows[] = $this->result->fetch_assoc(); > return $this->rows; > > 

But I cannot create this db set charset part, it’s always some kind of error 🙂

Читайте также:  Content img css styling

Your code works fine, but in your comment i’ve found a bug.

class Core extends mysqli < protected $db, $result; private $rows; public function __construct() < parent::__construct('127.0.0.1','root','pass','data'); if (mysqli_connect_error()) < throw new exception('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error()); >$this->set_charset('utf-8'); > public function query($sql) < $this->result = parent::query($sql); > > 

When you call the Core class as Object, automatically the connection with database will be created and will be set the charset UTF-8.

The class MySQLI was extended to reuse all your methods like $core_class_object->stmt_init();

PHP mysqli set_charset() Function, W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

PHP + SQL Server — How to set charset for connection?

I’m trying to store some data in a SQL Server database through php.

Problem is that special chars aren’t converted properly. My app’s charset is iso-8859-1 and the one used by the server is windows-1252.

Converting the data manually before inserting doesn’t help, there seems to be some conversion going on.

Running the SQL query ‘set char_convert off’ doesn’t help either.

Anyone have any idea how I can get this to work?

EDIT: I have tried ini_set(‘mssql.charset’, ‘windows-1252’); as well, but no result with that one either.

Client charset is necessary but not sufficient:

I searched for two days how to insert UTF-8 data (from web forms) into MSSQL 2008 through PHP. I read everywhere that you can’t, you need to convert to UCS2 first (like cypher’s solution recommends). On Windows SQLSRV said to be a good solution, which I couldn’t try, since I am developing on Mac OSX.

However, FreeTDS manual (what PHP mssql uses on OSX) says to add a letter «N» before the opening quote:

mssql_query("INSERT INTO table (nvarcharField) VALUES (N'űáúőűá球最大的采购批发平台')", +xon); 

According to this discussion, N character tells the server to convert to Unicode. https://softwareengineering.stackexchange.com/questions/155859/why-do-we-need-to-put-n-before-strings-in-microsoft-sql-server

I had the same problem and ini_set(‘mssql.charset’, ‘utf-8’) did not work for me. However, it worked in uppercase:

I suggest looking at the following points:

  1. Ensure that the columns that you’re storing the information in are nchar or nvarchar as char and nvarchar don’t support UCS-2 (SQLServer doesn’t store in UTF-8 format btw)
  2. If you’re connecting with the mssql library/extension for PHP, run: ini_set(‘mssql.charset’, ‘utf-8’); as there’s no function with a charset argument ( connect, query etc)
  3. Ensure that your browsers charset is also set to UTF-8

If ini_set(‘mssql.charset’, ‘UTF-8’); doesn’t help AND you don’t have root access to modify the system wide freetds.conf file, here’s what you can do:

1. Set up /your/local/freetds.conf file:

[sqlservername] host=192.168.0.56 port=1433 tds version=7.0 client charset=UTF-8 

2. Make sure your connection DSN is using the servername, not the IP:

'dsn' => 'dblib:host=sqlservername;dbname=yourdb 

3. Make FreeTDS to use your local freetds.conf file as an unprivileged user from php script via env variables:

putenv('FREETDSCONF=/your/local/freetds.conf'); 

PHP include html page charset problem, The problem is that the encoding of the html page is actually set by the http response header ‘Content-Type’, to fix what you need to do is add the following to your PHP file before any output (ie at the top).

Читайте также:  Python open another python file

How to set UTF-8 encoding for a PHP file

I have a PHP script called :

That displays some data in plain text:

Cz��� mowy: rzeczownik Przypadek: dope�niacz Rodzaj: şe�ski Liczba: mnoga 

As you can see in place of proper chars there are so «bushes». What i would like to do is display this in a way so that people see in browser proper UTF-8 characters.

You can encapsulate it in HMTL tags and set in meta UTF-8 encoding, but because the data received from this script will be processed further I don’t want to use any HTML tags, it should be only plain text result set.

So is there a way to inform browser that this file is UTF-8 without using meta tags?

PS. File is encoded in UTF-8 and if I manually change charset encoding in my browser to UTF-8 it displays ok, but what I want to acomplish is people to not be required to do so.

header('Content-type: text/plain; charset=utf-8'); 

Also note that setting a header to «text/plain» will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain .

header('Content-type: text/html; charset=utf-8'); 

Can return HTML and PHP as well. Not just text.

PHP, by default, always returns the following header: «Content-Type: text/html» (notice no charset), therefore you must use

Try this way header(‘Content-Type: text/plain; charset=utf-8’);

Character encoding — Setting charset in php, php character-encoding http-headers. Share. Follow asked Dec 7, 2011 at 18:49. abuduba abuduba. 4,866 7 7 gold badges 25 25 silver badges 42 42 bronze badges. Add a comment | 2 Answers Sorted by: Reset to default 2 If by ANSI you mean

Источник

Выставляем кодировку UTF-8

На сколько бы это глупо не казалось, но для удачного выставления кодировки необходимо выполнить целых 11(!) правил.
Хочу зарание предупредить, если какая-то из настроек в .htaccess повлечет за собой ошибку 500, это значит, что хостинг запретил менять этот параметр на сервере. В таком случае проверьте тот факт, что у Вас UTF-8 и в случае чего обратитесь к админам хостинга.
И для тех, кто попал на эту страницу с вопросами об Ajax: Ajax работает в кодировке UTF-8.

Правило №1: Указываем в HTML верстке в теге первой строчкой, кроме случаев, где мы будем использовать тег , так как он так же как и кодировка имеет приоритет над расположением, следующий код:

Читайте также:  Чаты html css телеграм

Правило №2: Указываем кодировку для PHP и самого файла, для этого нам необходимо выставить заголовок функцией header(). Выставляем его в самом начале нашего файла (абсолютно в самом начале), сразу после указания уровня вывода ошибок:

Правило №3: Кодировка для подключения к к БД MySQL. Устанавливается после подключения к БД и выбора бд (mysql_connect, mysql_select_db). Если у нас модуль mysql:

Правило №4: Кодировка в .htaccess:

Правило №5: Кодировка для библиотеки mb, начиная с версии php 5.4 можно не указывать, так как по умолчанию будет использоваться именно UTF-8. Ну а пока прописываем её в файле .htaccess:

php_value mbstring.internal_encoding UTF-8

Правило №6: При сохранении файлов (обязательно ВСЕХ!) выбрать кодировку UTF-8 without BOM, повторюсь, without BOM — это необходимая настройка, в противном случае Ваш сайт не будет работать как надо. Для тех, кто пользуется удобной программой DreamWeaver:
Modify => Page Properties => Title/Encoding и выставляем «Encoding: UTF-8», после чего нажимаем ReLoad, убираем галочку с BOM «Include Unicode Signature (BOM)». Apply + OK.
Модификации => Свойства страницы => Заголовок/Кодировка и выставляем кодировку UTF-8. Нажимаем «перезагрузить», убрали галочку с Подключить Юникод Сигнатуры (BOM). Применить и OK.

Правило №7: если на данный момент какой-то из текстов был введён на странице или в БД — его необходимо перенабрать. Дело в том, что символ в одной кодировке представляет один набор бит для русских символов, а в другой — другой. Именно поэтому необходимо его либо перенабрать, либо перекодировать. Современные программы имеют возможность перевести текст из одной кодировки в другую. Об этой возможности интересуйтесь в мануалах Ваших программ.

Правило №8: Есть исключение, когда текст приходит к Вам на страницу с другого сайта в другой кодировке. Тогда на PHP есть удобная функция для перевода из одной кодировки в другую:

Правило №9: Для строковых функций strlen, substr, необходимо использовать их аналоги на библиотеке mb_, а именно: mb_strlen, mb_substr, то есть к функции дописываем mb_ .

Правило №10: Для работы с регулярными выражениями необходимо указывать модификатор u . Это обязательный параметр!

Правило №11: Для CSS файлов указывается кодировка так:

В заключение скажу, что символы в кодировке WIN-1251 состоят из 1 байта, то есть 8 бит, а в свою очередь в кодировке UTF-8 символы могут состоять от 1 до 4 байт, всё дело в том, что кодировка UTF-8 позволяет создавать мультиязычные сайты, так как все существующие в мире символы в ней присутствуют.
Ради любопытства русская буква в кодировке UTF-8 занимает 2 байта, именно поэтому за 1 символ функция strlen возвращает длину 2, то есть 2 байта, а mb_strlen возвращает уже правильную длину в 1 символ.

Школа программирования © 2012-2023
imbalance_hero | inpost@list.ru , admin@school-php.com
account on phpforum | youtube channel

Источник

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