如何使用 PHP 跳过 XML 文件中的无效字符 [英] How to skip invalid characters in XML file using PHP

查看:14
本文介绍了如何使用 PHP 跳过 XML 文件中的无效字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PHP 解析 XML 文件,但收到一条错误消息:

I'm trying to parse an XML file using PHP, but I get an error message:

解析器错误:字符 0x0 超出允许范围

parser error : Char 0x0 out of allowed range in

我认为是因为XML的内容,我认为有一个特殊的符号☆",有什么想法可以解决吗?

I think it's because of the content of the XML, I think there is a speical symbol "☆", any ideas what I can do to fix it?

我也得到:

解析器错误:标签项行中的数据过早结束

parser error : Premature end of data in tag item line

可能导致该错误的原因是什么?

What might be causing that error?

我正在使用 simplexml_load_file.

I'm using simplexml_load_file.

我尝试找到错误行并将其内容粘贴为单个 xml 文件,它可以工作!!所以我仍然无法弄清楚是什么导致 xml 文件解析失败.PS 超过100M的超大xml文件,会不会导致解析错误?

I try to find the error line and paste its content as single xml file and it can work!! so I still cannot figure out what makes xml file parse fails. PS it's a huge xml file over 100M, will it makes parse error?

推荐答案

您是否可以控制 XML?如果是,请确保数据包含在 .. ]]> 块中.

Do you have control over the XML? If so, ensure the data is enclosed in <![CDATA[ .. ]]> blocks.

而且你还需要清除无效字符:

And you also need to clear the invalid characters:

/**
 * Removes invalid XML
 *
 * @access public
 * @param string $value
 * @return string
 */
function stripInvalidXml($value)
{
    $ret = "";
    $current;
    if (empty($value)) 
    {
        return $ret;
    }
 
    $length = strlen($value);
    for ($i=0; $i < $length; $i++)
    {
        $current = ord($value[$i]);
        if (($current == 0x9) ||
            ($current == 0xA) ||
            ($current == 0xD) ||
            (($current >= 0x20) && ($current <= 0xD7FF)) ||
            (($current >= 0xE000) && ($current <= 0xFFFD)) ||
            (($current >= 0x10000) && ($current <= 0x10FFFF)))
        {
            $ret .= chr($current);
        }
        else
        {
            $ret .= " ";
        }
    }
    return $ret;
}

这篇关于如何使用 PHP 跳过 XML 文件中的无效字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆