gpt4 book ai didi

PHP - 处理无效的 XML

转载 作者:可可西里 更新时间:2023-11-01 13:48:43 24 4
gpt4 key购买 nike

我正在使用 SimpleXML 加载一些 xml 文件(我没有编写/提供这些文件,也无法真正更改其格式)。

偶尔(例如,每 50 个左右的文件中有一个或两个文件)它们不会转义任何特殊字符(主要是 &,但有时也会出现其他随机的无效字符)。这会产生问题,因为 SimpleXML with php 只是失败了,而且我真的不知道有什么好的方法来处理解析无效的 XML。

我的第一个想法是将 XML 预处理为一个字符串,并将所有字段作为 CDATA 放入,这样它就可以工作,但出于某些不合理的原因,我需要处理的 XML 将其所有数据放入属性字段中。因此我不能使用 CDATA 的想法。 XML 的一个例子是:

 <Author v="By Someone & Someone" />

在使用 SimpleXML 加载它之前,最好的处理方法是什么以替换 XML 中的所有无效字符?

最佳答案

您需要的是使用 libxml 的内部错误来定位无效字符并相应地转义它们的东西。这是我如何编写它的模型。查看 libxml_get_errors() 的结果以获取错误信息。

function load_invalid_xml($xml)
{
$use_internal_errors = libxml_use_internal_errors(true);
libxml_clear_errors(true);

$sxe = simplexml_load_string($xml);

if ($sxe)
{
return $sxe;
}

$fixed_xml = '';
$last_pos = 0;

foreach (libxml_get_errors() as $error)
{
// $pos is the position of the faulty character,
// you have to compute it yourself
$pos = compute_position($error->line, $error->column);
$fixed_xml .= substr($xml, $last_pos, $pos - $last_pos) . htmlspecialchars($xml[$pos]);
$last_pos = $pos + 1;
}
$fixed_xml .= substr($xml, $last_pos);

libxml_use_internal_errors($use_internal_errors);

return simplexml_load_string($fixed_xml);
}

关于PHP - 处理无效的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com