使用curl方式实现get或post请求 将返回的XML 转成数组格式
/** * 使用curl方式实现get或post请求 * @param $url 请求的url地址 * @param $data 发送的post数据 如果为空则为get方式请求 * return 请求后获取到的数据 */ public function curlRequest($url, $data = '') { $ch = curl_init(); $params[CURLOPT_URL] = $url; //请求url地址 $params[CURLOPT_HEADER] = false; //是否返回响应头信息 $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回 $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向 $params[CURLOPT_TIMEOUT] = 30; //超时时间 if (!empty($data)) { $params[CURLOPT_POST] = true; $params[CURLOPT_POSTFIELDS] = $data; } $params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案 $params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文 curl_setopt_array($ch, $params); //传入curl参数 $content = curl_exec($ch); //执行 curl_close($ch); //关闭连接 return $content; }
# 将返回的XMl 转换为数组
$url = ""; $data = array( "Method" => '' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 500); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); $output = curl_exec($ch); //执行并获取数据 curl_close($ch); //将返回的XML转换为数组 $xml = simplexml_load_string($output); $xml = json_decode($xml, true);
function http_request($url, $data = null, $headers = array() ){ $curl = curl_init(); if(count($headers) >= 1){ curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if(!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); if(curl_errno($curl)) { print curl_error($curl); } $output = curl_exec($curl); curl_close($curl); return $output; }