![](/img/trans.png)
[英]Document labelled UTF-16 but has UTF-8 content in Entity PHP error
[英]PHP : How to manage “Document labelled UTF-16 but has UTF-8 content” error on simplexml_load_string()
語言: PHP 7.3 / Laravel 6.*
問題:我的系統收到來自第三方的 email,其中包含有關潛在客戶的信息。 其中之一向我們發送了包含 UTF-16 標簽但內容為 UTF-8 的數據。
目標:我想讓系統在收到數據時對其進行嘗試。 然后,如果發生錯誤,請嘗試其他方法。 我不想在每個請求上更改 UTF-16 字符串。
代碼:
$input = $request->all();
try {
$xml = simplexml_load_string($input['body-plain']);
throw new Exception();
} catch(Exception $e) {
try {
$input['body-plain'] = str_replace("UTF-16", "UTF-8", $input['body-plain']);
$xml = simplexml_load_string($input['body-plain']);
throw new Exception();
} catch(Exception $e) {
}
}
$prospect = $xml->prospect;
錯誤:
simplexml_load_string():實體:第 1 行:解析器錯誤:文檔標記為 UTF-16 但具有 UTF-8 內容
try {
$xml = simplexml_load_string($input['body-plain']); //This is the line where the error happen.
throw new Exception();
數據:
...
"body-plain" => """
<?xml version="1.0" encoding="UTF-16"?>
<?ADF version="1.0"?>
<adf>
<prospect>
<id source="language">Français</id>
<requestdate>2019-11-20T11:35:24-05:00</requestdate>
<vehicle interest="buy" status="Used">
...
結論:我不明白為什么當我這樣使用 try catch 時它不起作用。
有沒有辦法告訴 PHP 查看包含和 label 是否匹配?
PHP 使用的 XML 庫不是面向對象的,不會拋出異常。 此外,您在代碼中直接拋出自己的異常,確保每次都執行catch
塊。
第一步是禁用 libxml 的錯誤 output 。 然后檢查錯誤並采取適當的措施。
<?php
$input = $request->all();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($input['body-plain']);
$err = libxml_get_last_error();
// you'll need to confirm the error code, try `print_r($err);` here
if ($err->code === 5032) {
libxml_clear_errors();
$input['body-plain'] = str_replace("UTF-16", "UTF-8", $input['body-plain']);
$xml = simplexml_load_string($input['body-plain']);
}
if (libxml_get_last_error()) {
// something bad happened
}
$prospect = $xml->prospect;
可以在手冊中找到此信息以及一個小示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.