Как прописать кодировку utf 8 в html
Перейти к содержимому

Как прописать кодировку utf 8 в html

  • автор:

Declaring character encodings in HTML

You should always specify the encoding used for an HTML or XML page. If you don’t, you risk that characters in your content are incorrectly interpreted. This is not just an issue of human readability, increasingly machines need to understand your data too. A character encoding declaration is also needed to process non-ASCII characters entered by the user in forms, in URLs generated by scripts, and so forth. This article describes how to do this for an HTML file.

If you need to better understand what characters and character encodings are, see the article Character encodings for beginners . For information about declaring encodings for CSS style sheets, see CSS character encoding declarations .

Quick answer

Always declare the encoding of your document using a meta element with a charset attribute, or using the http-equiv and content attributes (called a pragma directive). The declaration should fit completely within the first 1024 bytes at the start of the file, so it’s best to put it immediately after the opening head tag.

It doesn’t matter which you use, but it’s easier to type the first one. It also doesn’t matter whether you type UTF-8 or utf-8 .

You should always use the UTF-8 character encoding. (Remember that this means you also need to save your content as UTF-8.) See what you should consider if you really cannot use UTF-8.

If you have access to the server settings, you should also consider whether it makes sense to use the HTTP header. Note however that, since the HTTP header has a higher precedence than the in-document meta declarations, content authors should always take into account whether the character encoding is already declared in the HTTP header. If it is, the meta element must be set to declare the same encoding.

You can detect any encodings sent by the HTTP header using the Internationalization Checker.

Details

What about the byte-order mark?

If you have a UTF-8 byte-order mark (BOM) at the start of your file then recent browser versions other than Internet Explorer 10 or 11 will use that to determine that the encoding of your page is UTF-8. It has a higher precedence than any other declaration, including the HTTP header.

You could skip the meta encoding declaration if you have a BOM, but we recommend that you keep it, since it helps people looking at the source code to ascertain what the encoding of the page is.

Should I declare the encoding in the HTTP header?

Use character encoding declarations in HTTP headers if it makes sense, and if you are able, for any type of content, but in conjunction with an in-document declaration.

Content authors should always ensure that HTTP declarations are consistent with the in-document declarations.

Pros and cons of using the HTTP header

One advantage of using the HTTP header is that user agents can find the character encoding information sooner when it is sent in the HTTP header.

The HTTP header information has the highest priority when it conflicts with in-document declarations other than the byte-order mark. Intermediate servers that transcode the data (ie. convert to a different encoding) could take advantage of this to change the encoding of a document before sending it on to small devices that only recognize a few encodings. It is not clear that this transcoding is much used nowadays. If it is, and it is converting content to non-UTF-8 encodings, it runs a high risk of loss of data, and so is not good practice.

On the other hand, there are a number of potential disadvantages:

It may be difficult for content authors to change the encoding information for static files on the server – especially when dealing with an ISP. Authors will need knowledge of and access to the server settings.

Server settings may get out of synchronization with the document for one reason or another. This may happen, for example, if you rely on the server default, and that default is changed. This is a very bad situation, since the higher precedence of the HTTP information versus the in-document declaration may cause the document to become unreadable.

There are potential problems for both static and dynamic documents if they are not read from a server; for example, if they are saved to a location such as a CD or hard disk. In these cases any encoding information from an HTTP header is not available.

Similarly, if the character encoding is only declared in the HTTP header, this information is no longer available for files during editing, or when they are processed by such things as XSLT or scripts, or when they are sent for translation, etc.

So should I use this method?

If serving files via HTTP from a server, it is never a problem to send information about the character encoding of the document in the HTTP header, as long as that information is correct.

On the other hand, because of the disadvantages listed above we recommend that you should always declare the encoding information inside the document as well. An in-document declaration also helps developers, testers, or translation production managers who want to visually check the encoding of a document.

(Some people would argue that it is rarely appropriate to declare the encoding in the HTTP header if you are going to repeat it in the content of the document. In this case, they are proposing that the HTTP header say nothing about the document encoding. Note that this would usually mean taking action to disable any server defaults.)

Working with polyglot and XML formats

XHTML5: An XHTML5 document is served as XML and has XML syntax. XML parsers do not recognise the encoding declarations in meta elements. They only recognise the XML declaration. Here is an example:

The XML declaration is only required if the page is not being served as UTF-8 (or UTF-16), but it can be useful to include it so that developers, testers, or translation production managers can visually check the encoding of a document by looking at the source.

Polyglot markup: A page that uses polyglot markup uses a subset of HTML with XML syntax that can be parsed either by an HTML or an XML parser. It is described in Polyglot Markup: A robust profile of the HTML5 vocabulary .

Since a polyglot document must be in UTF-8, you don’t need to, and indeed must not, use the XML declaration. On the other hand, if the file is to be read as HTML you will need to declare the encoding using a meta element, the byte-order mark or the HTTP header.

Since a declaration in a meta element will only be recognized by an HTML parser, if you use the approach with the content attribute its value should start with text/html; .

If you use the meta element with a charset attribute this is not something you need to consider.

Additional information

The information in this section relates to things you should not normally need to know, but which are included here for completeness.

Working with non-UTF-8 encodings

Using UTF-8 not only simplifies authoring of pages, it avoids unexpected results on form submission and URL encodings, which use the document’s character encoding by default. If you really can’t avoid using a non-UTF-8 character encoding you will need to choose from a limited set of encoding names to ensure maximum interoperability and the longest possible term of readability for your content.

Although these are normally called names, in reality they refer to the encodings, not the character sets. For example, the Unicode character set or ‘repertoire’ can be encoded in three different encoding schemes.

Until recently the IANA registry was the place to find names for encodings. The IANA registry commonly includes multiple names for the same encoding. In this case you should use the name designated as ‘preferred’.

The new Encoding specification now provides a list that has been tested against actual browser implementations. You can find the list in the table in the section called Encodings. It is best to use the names in the left column of that table.

Note, however, that the presence of a name in either of these sources doesn’t necessarily mean that it is OK to use that encoding. Several of the encodings are problematic. If you really can’t use UTF-8, you should carefully consider the advice in the article Choosing & applying a character encoding .

Do not invent your own encoding names preceded by x- . This is a bad idea since it limits interoperability.

Working with legacy HTML formats

HTML 4.01 doesn’t specify the use of the charset attribute with the meta element, but any recent major browser will still detect it and use it, even if the page is declared to be HTML4 rather than HTML5. This section is only relevant if you have some other reason than serving to a browser for conforming to an older format of HTML. It describes any differences from the Details section above.

HTML4: As mentioned just above, you need to use the pragma directive for full conformance with HTML 4.01, rather than the charset attribute.

XHTML 1.x served as text/html: Also needs the pragma directive for full conformance with HTML 4.01, rather than the charset attribute. You do not need to use the XML declaration, since the file is being served as HTML.

XHTML 1.x served as XML: Use the encoding declaration of the XML declaration on the first line of the page. Ensure there is nothing before it, including spaces (although a byte-order mark is OK).

The charset attribute on a link

HTML5 deprecated the use of the charset attribute on an a or link element, so you should avoid using it. It originated in the HTML 4.01 specification for use with the a , link and script elements and was supposed to indicate the encoding of the document you are linking to.

It was intended for use on an embedded link element like this:

Bad code. Don’t copy!

The idea was that the browser would be able to apply the right encoding to the document it retrieves if no encoding is specified for the document in any other way.

There were always issues with the use of this attribute. Firstly, it is not well supported by major browsers. One reason not to support this attribute is that if browsers do so without special additional rules it would be an XSS attack vector. Secondly, it is hard to ensure that the information is correct at any given time. The author of the document pointed to may well change the encoding of the document without you knowing. If the author still hasn’t specified the encoding of their document, you will now be asking the browser to apply an incorrect encoding. And thirdly, it shouldn’t be necessary anyway if people follow the guidelines in this article and mark up their documents properly. That is a much better approach.

This way of indicating the encoding of a document has the lowest precedence (ie. if the encoding is declared in any other way, this will be ignored). This means that you couldn’t use this to correct incorrect declarations either.

Working with UTF-16

According to the results of a Google sample of several billion pages, less than 0.01% of pages on the Web are encoded in UTF-16. UTF-8 accounted for over 80% of all Web pages, if you include its subset, ASCII, and over 60% if you don’t. You are strongly discouraged from using UTF-16 as your page encoding.

If, for some reason, you have no choice, here are some rules for declaring the encoding. They are different from those for other encodings.

The HTML5 specification forbids the use of the meta element to declare UTF-16, because the values must be ASCII-compatible. Instead you should ensure that you always have a byte-order mark at the very start of a UTF-16 encoded file. In effect, this is the in-document declaration.

Furthermore, if your page is encoded as UTF-16, do not declare your file to be "UTF-16BE" or "UTF-16LE", use "UTF-16" only. The byte-order mark at the beginning of your file will indicate whether the encoding scheme is little-endian or big-endian . (This is because content explicitly encoded as, say, UTF-16BE should not use a byte-order mark; but HTML5 requires a byte-order mark for UTF-16 encoded pages.)

The XML declaration

The XML declaration is defined by the XML standard. It appears at the top of an XML file and supports an encoding declaration . For example:

An XML declaration is required for a document parsed as XML if the encoding of the document is other than UTF-8 or UTF-16 and if the encoding is not provided by a higher level protocol , ie. the HTTP header.

This is significant, because if you decide to omit the XML declaration you must choose either UTF-8 or UTF-16 as the encoding for the page if it is to be used without HTTP!

You should use an XML declaration to specify the encoding of any XHTML 1.x document served as XML.

It can be useful to use an XML declaration for web pages served as XML, even if the encoding is UTF-8 or UTF-16, because an in-document declaration of this kind also helps developers, testers, or translation production managers ascertain the encoding of the file with a visual check of the source code.

Using the XML declaration for XHTML served as HTML. XHTML served as HTML is parsed as HTML, even though it is based on XML syntax, and therefore an XML declaration should not be recognized by the browser. It is for this reason that you should use a pragma directive to specify the encoding when serving XHTML in this way*.

* Conversely, the pragma directive, though valid, is not recognized as an encoding declaration by XML parsers.

On the other hand, the file may also be used at some point as input to other processes that do use XML parsers. This includes such things as XML editors, XSLT transformations, AJAX, etc. In addition, sometimes people use server-side logic to determine whether to serve the file as HTML or XML. For these reasons, if you aren’t using UTF-8 or UTF-16 you should add an XML declaration at the beginning of the markup, even if it is served to the browser as HTML. This would make the top of a file look like this:

If you are using UTF-8 or UTF-16, however, there is no need for the XML declaration, especially as the meta element provides for visual inspection of the encoding by people processing the file.

Catering for older browsers. If anything appears before the DOCTYPE declaration in Internet Explorer 6, the page is rendered in quirks mode. If you are using UTF-8 or UTF-16 you can omit the XML declaration, and you will have no problem.

If, however, you are not using these encodings and Internet Explorer 6 users still count for a significant proportion of your readers, and if your document contains constructs that are affected by the difference between standards mode vs. quirks mode, then this may be an issue. If you want to ensure that your pages are rendered in the same way on all standards-compliant browsers, you will have to add workarounds to your CSS to overcome the differences.

There may also be some other rendering issues associated with an XML declaration, though these are probably only an issue for much older browsers. The XHTML specification warns that processing instructions are rendered on some user agents. Also, some user agents interpret the XML declaration to mean that the document is unrecognized XML rather than HTML, and therefore may not render the document as expected. You should do testing on appropriate user agents to decide whether this will be an issue for you.

Of course, as mentioned above, if you use UTF-8 or UTF-16 you can omit the XML declaration and the file will still work as XML or HTML. This is probably the simplest solution.

Кодировка HTML-документа

Каждый вебмастер сталкивался с проблемой неправильного отображения текста на странице: Кракозябры

Это случается по одной из следующих причин: текст имеет кодировку, которая не соответствует указанной в документе или передаваемой сервером; кодировка документа указано неверно; сервер отдаёт документ, указывая неправильную кодировку.

Далее везде будет применяться кодировка UTF-8, так как она наиболее универсальная и её рекомендуется использовать повсеместно.

Текст

Первым делом нужно проверить кодировку текста в документе. Рассмотрим как это делается в Блокноте и Notepad++.

Блокнот

  1. Открываем Блокнот: Win+R → notepad ; и копируем в него код страницы.
  2. Кликаем Файл → Сохранить как. или нажимаем Ctrl+S .
  3. В поле Имя файла вводим название документа с расширением.
  4. В поле Тип файла выбираем Все файлы , так как иначе не учтётся введённое расширение и файл сохраниться в формате txt (это зависит от настроек операционной системы).
  5. Ставим кодировку UTF-8 и сохраняем документ.

Notepad++

  1. Открываем страницу в Notepad++.
  2. Выбираем Кодировки → Преобразовать в UTF-8 без BOM .
  3. Сохраняем документ.

Нужно выбрать именно Преобразовать в UTF-8 без BOM , а не Кодировать в UTF-8 (без BOM) .

Сервер

На реальном хостинге никто не предоставит возможность изменять конфигурацию сервера своим клиентам, поэтому этот момент пропускаем.

Чтобы указать кодировку, с которой сервер должен отдавать HTML-документы, нужно сделать следующее (на примере использования Блокнота): открыть Блокнот: Win+R → notepad ; и написать в нём следующую строку: AddDefaultCharset UTF-8 кликнуть Файл → Сохранить как. или нажать Ctrl+S ; в поле Имя файла ввести .htaccess ; в поле Тип файла выбрать Все файлы и сохранить файл в корень сайта. Сохранение файла с расширением .htaccess через Блокнот

Файлы без имени с расширением .htaccess позволяют конфигурировать некоторые опции сервера Apache.

Если всё сделано правильно, то текст на странице должен отобразиться правильно, то есть так, как он представлен в текстовом редакторе.

Как настроить кодировку сайта самостоятельно

Разбираем, на что влияет кодировка, нужно ли указывать ее самостоятельно, и почему могут появиться так называемые «кракозябры» на сайте.

Зачем нужна кодировка

Кодировка (Charset) — способ отображения кода на экране, соответствие набора символов набору числовых значений. О ней сообщает строка Content-Type и сервер в header запросе.

Несовпадение кодировок сервера и страницы будет причиной появления ошибок. Если они не совпадают, информация декодируется некорректно, так что контент на сайте будет отображаться в виде набора бессвязных букв, иероглифов и символов, в народе называемых «кракозябрами». Такой текст прочитать невозможно, так что пользователь просто уйдет с сайта и найдет другой ресурс. Или останется, если ему не очень важно содержание:

На сайте слетела кодировка, примерСтудентка списывала реферат с формулами, а на сайте слетела кодировка. Реальная история

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

Кодировка влияет на SEO?

Разберемся, как кодировка на сайте влияет на индексацию в Яндекс и Google.

Позиция Google такая же. Поисковики не рассматривают Charset как фактор ранжирования или сигнал для индексирования, тем не менее, она косвенно влияет на трафик и позиции.

Если кодировка сервера не совпадает с той, что указана на сайте, пользователи увидят нечитабельные символы вместо контента. На таком сайте сложно что-либо понять, так что скорее всего пользователи сбегут, а на сайте будут расти отказы.

Некорректно указана кодировка на сайтеПример страницы со слетевшей кодировкой

Поэтому она важна для SEO, хоть и влияет на него косвенно через поведенческие. Пользователи должны видеть читабельный текст на человеческом языке, чтобы работать с сайтом.

Виды кодировок

Существует довольно много видов, но сейчас распространены два:

Unicode Transformation Format — универсальный стандарт кодирования, который работает с символами почти всех языков мира. Символы могут занимать от 1 до 4 байт, такое кодирование позволяет создавать мультиязычные сайты.

Есть несколько вариантов — UTF-8, 16, 32, но чаще используют восьмибитное.

Windows-1251

Этот вид занимает второе место по популярности после UTF-8. Windows-1251 — кодирование для кириллицы, созданное на базе кодировок, использовавшихся в русификаторах операционной системы Windows. В ней есть все символы, которые используются в русской типографике, кроме значка ударения. Символы занимают 1 байт.

Выбор кодировки остается на усмотрение веб-мастера, но UTF-8 используют намного чаще — ее поддерживают все популярные браузеры и распознают поисковики, а еще ее удобнее использовать для сайтов на разных языках.

Как определить кодировку на сайте

Определить кодировку страницы своего или чужого сайта можно через исходный код страницы. Откройте страницу сайта, выберите «Просмотр кода страницы» (сочетание горячих клавиш Ctrl+U» в Google Chrome) и найдите упоминание «charset» внутри тега head.

На странице сайта используется кодировка UTF-8:

Как посмотреть, какая кодировка на сайтеУказание кодировки в коде страницы

Узнать вид кодирования можно с помощью сервиса для анализа сайта. Сервис проверяет в том числе и техническую сторону ресурса: анализирует серверную информацию, определяет кодировку, проверяет редиректы и другие пункты.

Как определить кодировку на сайтеФрагмент анализа

С помощью этого же сервиса можно проверить корректность указанного кодирования на конкретных страницах. Сервис проверяет кодировку сервера и сравнивает ее с той, которая указана на внутренней странице. Найденные ошибки он покажет в результатах проверки, и вы сразу узнаете, где нужно исправить.

Проверка кодировки на сайтеОтчет

Проверить кодировку еще можно через сервис Validator.w3, о котором писали в статье о проверке валидации кода. Нужная надпись находится внизу страницы.

Сервис для проверки кодировки на сайтеКодировка сайта в валидаторе

Если валидатор не обнаружит Charset, он покажет ошибку:

Некорректная кодировка, примерОшибка указания кодировки

Но валидатор работает не точно: он проверяет только синтаксис разметки, поэтому может не показать ошибку, даже если кодирование указано неправильно.

Если кодировка не отображается

Если вы зашли на чужой сайт с абракадаброй, а вам все равно очень интересно почитать контент, то в Справке Google объясняют, как исправить кодирование текста через браузер.

О проблеме возникновения абракадабры на вашем сайте будут сигнализировать метрики поведения: вырастут отказы, уменьшится глубина просмотров. Но скорее всего вы и раньше заметите, что что-то пошло не так.

Главное правило — для всех файлов, скриптов, баз данных сайта и сервера должна быть указана одна кодировка. Ошибка может возникнуть, если вы случайно указали на сайте разные виды кодировки.

Яндекс советует использовать одинаковую кодировку для страниц и кириллических адресов структуры. К примеру, если робот встретит ссылку href=»/корзина» на странице с кодировкой UTF-8, он сохранит ее в этом же UTF-8, так что страница должна быть доступна по адресу «/%D0%BA%D0%BE%D1%80%D0%B7%D0%B8%D0%BD%D0%B0».

Где указать кодировку сайта

У всех таблиц, колонок, файлов, сервера и вообще всего, что связано с сайтом, должна быть одна кодировка. Нужно привести все к единому виду:

  • кодировка в мета-теге;
  • кодировка в .htaccess;
  • кодировка документа;
  • кодировка в базе данных MySQL.

Кодировка в мета-теге

Добавьте указание кодировки в head файла шаблона сайта.

При создании документа HTML укажите тег meta в начале в блоке head. Некоторые браузеры могут не распознать указание кодировки, если оно будет ниже.

Мета-тег может выглядеть так:

В HTML5 они эквивалентны.

Где указывать кодировку на сайтеТег кодировки в HTML

В темах WordPress обычно тег «charset» с кодировкой указан по умолчанию, но лучше проверить.

Кодировка в файле httpd.conf

Инструкции для сервера находятся в файле httpd.conf, обычно его можно найти на пути «/usr/local/apache/conf/».

Если вам нужно сменить кодировку Windows-1251 на UTF-8, замените строчку «AddDefaultCharset windows-1251» на «AddDefaultCharset utf-8».

Убедитесь, что сервер не передает HTTP-заголовки с конфликтующими кодировками.

Кодировка в .htaccess

Добавьте кодировку в файл .htaccess:

  1. Откройте панель управления хостингом.
  2. Перейдите в корневую папку сайта.
  3. В файле .htaccess добавьте в самое начало код:
    1. для указания кодировки UTF-8 — AddDefaultCharset UTF-8;
    2. для указания кодировки Windows-1251 — AddDefaultCharset WINDOWS-1251.

    Кодировка документа

    Готовые файлы HTML важно сохранять в нужной кодировке сайта. Узнать текущую кодировку файла можно через Notepad++: откройте файл и зайдите в «Encoding». Меняется она там же: чтобы сменить кодировку на UTF-8, выберите «Convert to UTF-8 without BOOM». Нужно выбрать «без BOOM», чтобы не было пустых символов.

    Кодировка Базы данных

    Выбирайте нужную кодировку сразу при создании базы данных. Распространенный вариант — «UTF-8 general ci».

    Где менять кодировку у БД:

    1. Кликните по названию нужной базы в утилите управления БД phpMyAdmin и откройте ее.
    2. Кликните на раздел «Операции»:
    3. Введите нужную кодировку для базы данных MySQL:
    4. Перейдите на сайт и очистите кэш.

    Для всех таблиц, колонок, файлов, сервера и вообще всего, что связано с сайтом, должна быть одна кодировка.

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

    Проблема может не решиться, если все дело в кодировке подключения к базе данных. Что делать:

    1. Подключитесь к серверу с правами mysql root пользователя:
      mysql -u root -p
    2. Выберите нужную базу:
      USE имя_базы;
    3. Выполните запрос:
      SET NAMES ‘utf8’;

    Если вы хотите указать Windows-1251, то пишите не «utf-8», а «cp1251» — обозначение для кодировки Windows-1251 у MySQL.

    HTML кодировка страницы. В какой кодировке сохранять web-страницу? Урок №14

    Бывали ли у вас ситуации, когда на web-странице вместо читабельного текста открывались кракозябры? Я уверен, что бывали или, по крайне мере, вы видели их на других сайтах. Если не видели, посмотрите на пример снизу:

    HTML кодировка страницы. В какой кодировке сохранять web-страницу

    Что такое HTML кодировка?
    HTML кодировка – это таблицы соответствия кодов и символов алфавита. То есть, наш компьютер по кодировке поменяет код на понятные читабельные буквы.

    Что такое HTML кодировка?

    Популярные кодировки.
    На сегодняшний день существуют две самые популярные кодировки в русскоязычном интернете. Это кодировка windows-1251 и utf-8. Частенько веб-мастерам приходится выбирать, в какой кодировке делать им веб-страничку.

    В какой кодировке следует сохранять HTML файл?
    Большинство веб-мастеров выбирают кодировку utf-8. И это верный выбор, так как в кодировке utf-8 имеются различные знаки ( ↓↑ и т. д.), а также есть масса разнообразных специфических символов. Кстати, основная часть движков, как Joomla, WordPress, Drupal работает на кодировке utf-8.

    Поэтому я рекомендую вам сохранять HTML файлы в кодировке utf-8 .

    Как задать кодировку UTF-8 для файла?
    Чтобы задать кодировку для HTML файла, используют различные редакторы. Я пользуюсь текстовым редактором Notepad++.
    Откройте текстовый редактор Notepad++.
    Если нужно, создайте новый документ.
    Перейдите в меню сверху по вкладке « Кодировки » => « Кодировать в UTF-8 (без BOM) »:

    Как задать кодировку UTF-8 для файла?

    Чтобы сообщить браузеру, в какой кодировке HTML файл, существует специальный META-тег

    В HTML документе это будет выглядеть вот так:

    Как задать кодировку windows-1251 для файла?
    Откройте текстовый редактор Notepad++.
    Если нужно, создайте новый документ.
    Перейдите в меню сверху по вкладке « Кодировки » => « Кодировать в ANSI »:

    Как задать кодировку windows-1251 для файла?

    Чтобы сообщить браузеру, в какой кодировке HTML файл, существует специальный META-тег

    В HTML документе это будет выглядеть вот так:

    Пример перекодировки файла из windows-1251 в utf-8
    Если в HTML документе был прописан код в кодировке windows-1251 (ANSI), а вам нужно перекодировать на utf-8 (или на оборот), тогда сделайте так:
    Откройте текстовый редактор Notepad++. В текстовом редакторе перейдите в меню сверху по вкладке « Кодировки » => « Преобразовать в UTF-8 (без BOM) »:

    Пример перекодировки файла из windows-1251 в utf-8

    Внимание , если бы вы нажали « Кодировать в UTF-8 (без BOM) », то в результате вы бы увидели вместо любимого русского текста, красивые караказябли .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *