如果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));
}
PHP 解析xml(包含非英文字符)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.