Xml encoding error как исправить

First of all, make sure that your XML file is indeed UTF-8 encoded. If not specify the encoding as the second parameter to XMLReader::open().

If the encoding error is due a real malformed byte sequence in an UTF-8 document and if you’re using PHP > 5.2.0 you could pass LIBXML_NOERROR and/or (depending on the error level) LIBXML_NOWARNING as a bitmask to the third parameter of XMLReader::open():

$xml = new XMLReader(); 
$xml->open('myxml.xml', null, LIBXML_NOERROR | LIBXML_NOWARNING); 

If your’re using PHP > 5.1.0 you can tweak the libXML error-handling.

// enable user error handling
libxml_use_internal_errors(true);
/* ... do your XML processing ... */
$errors = libxml_get_errors();
foreach ($errors as $error) {
    // handle errors here
}
libxml_clear_errors();

I actually don’t know if the preceding two work-arounds actually allow XMLReader to continue reading in case of an error or if they only suppress the error output. But it’s worth a try.


Responding to comment:

libXML defines XML_PARSE_RECOVER (1) but ext/libxml does not expose this constant as a PHP constant. Perhaps it’s possible to pass the integer value 1 to the $options parameter.

$xml = new XMLReader(); 
$xml->open('myxml.xml', null, LIBXML_NOERROR | LIBXML_NOWARNING | 1); 

Текст должен быть в формате UTF-8. Не используйте двойное кодирование.

В Merchant Center поддерживаются такие стандарты кодировки, как UTF-8, UTF-16, Latin-1 и ASCII. Если вы не знаете, какой именно тип кодировки используется в вашем файле, выберите параметр Определять автоматически.

Если вы сохраняете файл в программе «Блокнот», нажмите Сохранить как и выберите ANSI или UTF-8 в поле Кодировка. Если формат кодировки файла отличается от указанных выше, файл не будет обработан.

Важное примечание. Если в XML-файле используется кодировка Latin-1 или UTF-16, необходимо указать это в нем. Для этого в первой строке фида замените фрагмент <?xml version=" 1.0"?> на одно из следующих значений:

  • для Latin-1: <?xml version="1.0" encoding="ISO-8859-1"?>;
  • для UTF-16: <?xml version="1.0" encoding="UTF-16"?>.

Инструкции

Шаг 1. Проверьте список товаров с ошибками

  1. Войдите в аккаунт Merchant Center.
  2. Перейдите на вкладку Товары в меню навигации и выберите Диагностика.
  3. Нажмите Проблемы с товарами. Откроется список затронутых позиций.

Как скачать список всех затронутых товаров (в формате .csv)

Как скачать список всех товаров с конкретной проблемой (в формате .csv)

  • Найдите проблему в одноименном столбце и нажмите на значок скачивания Download в конце строки.

Как посмотреть 50 самых популярных товаров с определенной проблемой

  • Найдите проблему в одноименном столбце и нажмите Посмотреть примеры в столбце «Затронутые товары».

Шаг 2. Задайте для текста формат UTF-8

  1. Отфильтруйте данные так, чтобы в столбце Issue title (Название проблемы) отображались только значения Invalid UTF-8 encoding (Недопустимая кодировка UTF-8).
  2. Проверьте сведения, указанные для товаров с этой проблемой. Исправьте данные в фиде так, чтобы для значений основных атрибутов был использован формат UTF-8.

Шаг 3. Повторно загрузите фид

  1. После изменения данных о товаре отправьте их повторно, выбрав один из перечисленных ниже способов.
    • Добавить фид напрямую
    • Как отправить данные с помощью Content API
    • Как импортировать данные с платформы электронной торговли
  2. Перейдите на страницу «Диагностика» и убедитесь, что проблема решена.

    Обратите внимание, что изменения на этой странице могут появиться не сразу.

Эта информация оказалась полезной?

Как можно улучшить эту статью?

Please note! This page describes the nature of the error using a hypothetical example and not the erroneous data of the input test file. You should however be able to apply this information to your error case.

Error description:

XML Encoding error is given when validator finds something to be wrong with the encoding of the file. 

There are two aspects when in comes to an encoding of XML file:

  • The encoding XML file is using
  • The encoding reported in the XML declaration within the file

The actual encoding is selected when the file is saved by the system/program producing the file. The encoding within XML declaration is the attribute «encoding» in the first line of XML. Example below:

   <?xml version=»1.0″ encoding=»UTF-8″?>  

It is worth noting that capitalisation does not matter in the value, «UTF-8» is the same as «utf-8». Encoding UTF-8 is used in this example as it is mandated to be used in ISO 20022 payments.

Therefore, possible causes for getting this error are:

  • Encoding given in XML declaration does not match with actual file encoding
  • No XML declaration is found. Possible reasons for this include:
    • XML declaration is not given in the payment message or is not given in the first line
    • Input file is not a payment message or not in XML format

To save a file in another encoding external program has to be used, e.g. notepad.exe allows saving to UTF-8 and notepad++ allows more exhaustive encoding modification.

It is worth noting that revaldate feature in validator is not able to see the original encoding of the file and treats the file shown in the report to be in UTF-8 format. Therefore it may happen that this error «fixes itself» if the cause of error was a mismatch between file encoding and encoding reported in the file.

Short explanation about encoding here

  • Remove From My Forums
  • Question

  • the below xml sql server could not parse

    DECLARE @INPUTXML XML = ‘<?xml version=»1.0″ encoding=»utf-16″?>
    <Lineitems>
      <Lineitem>
        <Ticker>TER</Ticker>
        <ID>0</ID>
        <LineItem>Net Revenue</LineItem>
        <XFundCode>TRIN</XFundCode>
        <UserID>TDP</UserID>
      </Lineitem>
      <Lineitem>
        <Ticker>TER</Ticker>
        <ID>0</ID>
        <LineItem>Cost of Revenue</LineItem>
        <XFundCode>XXP</XFundCode>
        <UserID>TDP</UserID>    
      </Lineitem>
    </Lineitems>’;

    but when add N before xml then it can parse. so tell me what is the meaning of N ?

    thanks

Answers

  • Hi Sudip_inn, 

    N is used to be sure that you prefix Unicode string literals with an N prefix. An nvarchar column can store any Unicode data. A varchar column is restricted to an 8-bit codepage. Codepage incompatabilities are a pain,
    and Unicode is the cure for codepage problems. 

    All modern operating systems and development platforms use Unicode internally. By using nvarchar rather than varchar, you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors.
    And recovery from conversion errors is a non-trivial problem.

    So in your example , if you use N (nvarchar or nchar ), it will  parse successfully.  For more information , please check nchar
    and nvarchar (Transact-SQL)

    Best Regards,

    Rachel 


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by

      Wednesday, March 18, 2020 8:44 AM

  • but when add N before xml then it can parse. so tell me what is the meaning of N ?

    A string literal without N, ‘like this’ is of type varchar, which means that value is in the code page of the default collation for the database. A string literal with N, N’like this’ is an nvarchar literal, which is a Unicode string encoded
    in UTF-16. And since you say in the prologue of the document that the encoding is UTF-16, you need the N here.


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Marked as answer by
      Sudip_inn
      Wednesday, March 18, 2020 8:45 AM

  • How N is related with xml parsing…not clear.

    With varchar the encoding is the same as the code page of the collation, for instance iso-8859-1. With nvarchar, the encoding is always UTF-16.


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Marked as answer by
      Sudip_inn
      Wednesday, March 18, 2020 7:10 PM

Здравствуйте, братья! Сегодня наткнулся на непонятную проблему. Я перевёл свой Java проект с maven’a на graddle. И всё хорошо, но почему-то XML файлы стали сохранятся в неправильной кодировке… При сохранении их в UTF-8 получается вот это:

<?xml version="1.0" encoding="utf-8"?>
<sky>
  <mechanism name="33">
    <abilities>
      <ability name="�����������1" />
      <ability name="22" />
    </abilities>
  </mechanism>
</sky>

А при сохранении в windows-1251 вот это:

<?xml version="1.0" encoding="windows-1251"?>
<sky>
  <mechanism name="33">
    <abilities>
      <ability name="Проверка" />
      <ability name="22" />
    </abilities>
  </mechanism>
</sky>

Эти файлы генерируются моей программой в автоматическом режиме с помощью этого метода:

public void save(String path) throws IOException
	{
		Document document = new Document();
		document.setRootElement(getXMLElement());

		XMLOutputter outputter = new XMLOutputter();
		outputter.setFormat(Format.getPrettyFormat().setEncoding("windows-1251")); //utf-8 здесь работает неверно
		outputter.output(document, new FileWriter(path));
	}

Т.е. при сохранении в windows-1251 всё нормально, а при utf-8 — кракозябры. Такого раньше не было. Сначала я подумал что это криво работает библиотека для парсинга XML. Я использовал dom4j. Но затем я перешел на jdom2 и ситуация осталась прежней. Сохраненный программой файл ей же не открывается. Однако если вручную исправить xml-файл, то всё нормально. Я подозреваю что хотя кодировка выставлена в utf-8 программа всё-равно пишет в windows-1251. Видимо проблема где-то в настройках проекта, но где — я ума не приложу. Я использую Intellij IDEA. Помогите пожалуйста!

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти хорошего поставщика одежды для продажи
  • Лобзик макита пилит криво как исправить
  • Как найти ямы на озере зимой
  • Как найти объем сыра
  • Как исправить ошибку учетной записи в майнкрафт

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии