tp5 處理xml 數據

//xml請求方法node

public function docommon($url,$data){
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:text/xml; charset=utf-8"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//Post提交的數據包
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, 0);
ob_start();
$result = curl_exec($ch);
$str=ob_get_contents();
ob_clean();
curl_close($ch);
return $str;
}
//$arr 爲請求到的數據
$arr = $this->docommon($url,$data);
// 使用domdocument 來操做xml
$dom = new \DOMDocument();
// 解析xml類
$dom->loadXML($arr);
// 處理xml數據
$zarr=getArray($dom->documentElement);

//xml 轉爲arrayfunction getArray($node) {    $array = false;    if ($node->hasAttributes()) {        foreach ($node->attributes as $attr) {            $array[$attr->nodeName] = $attr->nodeValue;        }    }    if ($node->hasChildNodes()) {        if ($node->childNodes->length == 1) {            $array[$node->firstChild->nodeName] = getArray($node->firstChild);        } else {            foreach ($node->childNodes as $childNode) {                if ($childNode->nodeType != XML_TEXT_NODE) {                    $array[$childNode->nodeName][] = getArray($childNode);                }            }        }    } else {        return $node->nodeValue;    }    return $array;}
相關文章
相關標籤/搜索