【问题标题】:PHP : How to manage "Document labelled UTF-16 but has UTF-8 content" error on simplexml_load_string()PHP:如何管理 simplexml_load_string() 上的“文档标记为 UTF-16 但具有 UTF-8 内容”错误
【发布时间】:2019-11-20 17:19:47
【问题描述】:

语言: PHP 7.3 / Laravel 6.*

问题:我的系统收到来自第三方的电子邮件,其中包含有关潜在客户的信息。其中一个向我们发送包含 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 查看包含和标签匹配?

【问题讨论】:

  • 您是否在 Google Document labelled UTF-16 but has UTF-8 content 上搜索过一些结果,看看它们是否有帮助?
  • 我做到了。大多数解决方案是替换字符串,就像我在第二次尝试代码时所做的那样。这也是我拥有它的原因,但正如我所提到的,我不想对每个请求都这样做。

标签: php xml


【解决方案1】:

PHP 使用的 XML 库不是面向对象的,不会抛出异常。此外,您可以在代码中直接抛出自己的异常,确保每次都执行 catch 块。

第一步是disable libxml's error output。然后check for errors 并采取适当的行动。

<?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;

可以在the manual 中找到此信息以及一个小示例。

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2018-07-24
    • 2015-12-06
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多