PHP 解析xml(包含非英文字符)

如果XML格式不正确 返回错误异常
用递归方式解析XML
function getXMLDom($sXMLStr) {
    global $LINEFEED;
    $sXML_UTF8 = utf8_encode($sXMLStr);
    try {
        $oXML = @new SimpleXMLElement($sXML_UTF8);
    } catch (Exception $e) {
        return  $e->getMessage(); //XML格式不正确
    }
    $aXML = simpleXML2Array($oXML);
    return $aXML;
}

function simpleXML2Array($oXML) {
    if ("SimpleXMLElement" === get_class($oXML)) {
        $attri = $oXML->attributes();
        foreach ($attri as $key => $value) {
            if ($value) {
                $a[strtoupper($key)] = trim((string) utf8_decode($value));//节点属性值
            }
        }
        $x = $oXML;
        $oXML = get_object_vars($oXML);//子节点数组
    }
    if (is_array($oXML)) {
        if (0 === count($oXML)) {
            return trim((string) utf8_decode($x));
        }
        foreach ($oXML as $key => $value) {
            $r[strtoupper($key)] = simpleXML2Array($value);//遍历子节点
        }
        if (isset ($a)) {
            $r["@"] = $a;//节点属性数组
        }
        return $r;
    }
    return trim((string) utf8_decode($oXML));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值