如果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));
}
用递归方式解析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));
}