tp5 处理xml 数据

//xml请求方法

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 转为array
function 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;
}





posted @ 2018-03-20 10:34  创行客  阅读(788)  评论(0编辑  收藏  举报