PHP - 处理无效的XML

Pau*_*aul 5 php xml simplexml

我正在使用SimpleXML加载一些xml文件(我没有写/提供,并且无法真正改变格式).

偶尔(例如,每50个左右有一个或两个文件),他们不会逃避任何特殊字符(大多数情况下,但有时也是其他随机无效的字符).这创建并发布,因为带有php的SimpleXML失败了,我真的不知道处理解析无效XML的任何好方法.

我的第一个想法是将XML预处理为一个字符串并将所有字段放在CDATA中以便它可以工作,但是由于某种不正当的原因,我需要处理的XML将所有数据放在属性字段中.因此我不能使用CDATA的想法.XML的一个例子是:

 <Author v="By Someone & Someone" />
Run Code Online (Sandbox Code Playgroud)

在使用SimpleXML加载之前,最好的方法是从XML中替换所有无效字符?

Jos*_*vis 7

您需要的是使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • 发布一个计算机位置的例子会很方便! (2认同)