PHP 解析xml(包含非英文字符)
生活随笔
收集整理的這篇文章主要介紹了
PHP 解析xml(包含非英文字符)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如果XML格式不正確 返回錯(cuò)誤異常
用遞歸方式解析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));//節(jié)點(diǎn)屬性值
?? ??? ??? ?}
?? ??? ?}
?? ??? ?$x = $oXML;
?? ??? ?$oXML = get_object_vars($oXML);//子節(jié)點(diǎn)數(shù)組
?? ?}
?? ?if (is_array($oXML)) {
?? ??? ?if (0 === count($oXML)) {
?? ??? ??? ?return trim((string) utf8_decode($x));
?? ??? ?}
?? ??? ?foreach ($oXML as $key => $value) {
?? ??? ??? ?$r[strtoupper($key)] = simpleXML2Array($value);//遍歷子節(jié)點(diǎn)
?? ??? ?}
?? ??? ?if (isset ($a)) {
?? ??? ??? ?$r["@"] = $a;//節(jié)點(diǎn)屬性數(shù)組
?? ??? ?}
?? ??? ?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));//節(jié)點(diǎn)屬性值
?? ??? ??? ?}
?? ??? ?}
?? ??? ?$x = $oXML;
?? ??? ?$oXML = get_object_vars($oXML);//子節(jié)點(diǎn)數(shù)組
?? ?}
?? ?if (is_array($oXML)) {
?? ??? ?if (0 === count($oXML)) {
?? ??? ??? ?return trim((string) utf8_decode($x));
?? ??? ?}
?? ??? ?foreach ($oXML as $key => $value) {
?? ??? ??? ?$r[strtoupper($key)] = simpleXML2Array($value);//遍歷子節(jié)點(diǎn)
?? ??? ?}
?? ??? ?if (isset ($a)) {
?? ??? ??? ?$r["@"] = $a;//節(jié)點(diǎn)屬性數(shù)組
?? ??? ?}
?? ??? ?return $r;
?? ?}
?? ?return trim((string) utf8_decode($oXML));
}
轉(zhuǎn)載于:https://www.cnblogs.com/softbird/archive/2006/08/08/471340.html
超強(qiáng)干貨來(lái)襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的PHP 解析xml(包含非英文字符)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Response.Redirect 与
- 下一篇: ASP.NET 2.0+Atlas编写鼠