繁体   English   中英

PHP:如何管理 simplexml_load_string() 上的“文档标记为 UTF-16 但具有 UTF-8 内容”错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM