1、使用file_get_contents php
這裏咱們以發送xml格式的字符串到某個網址爲例。post的數據$pdata裏面有3個字段 app
/** * 整理數據並調用posttohost()方法 */ public function postData($url,$xml){ $xml = preg_replace("/[\n\t\s]+/",'',$xml); $digest = md5($xml.$this->key); $xml = iconv('UTF-8','GBK',$xml);//注意,簽名要在轉碼前,不然會報錯 $pdata = array( 'data_Isdigest' => 'Y', 'logistics_interface' => $xml, 'data_digest' => strtoupper($digest) ); $res = self::posttohost($url,$pdata); var_dump($res); } /** * 經過file_get_contents方式發送 */ public function posttohost($url, $pdata = array()){ $content = http_build_query($pdata);//生成 URL-encode 以後的請求字符串 $content_length = strlen($content); $options = array( 'http' => array( 'method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded; charset=gbk;\r\n". "Content-length: $content_length\r\n", 'content' => $content ) ); return file_get_contents($this->url, false, stream_context_create($options));//stream_context_create建立資源流上下文 }
2、使用curl curl
/** * 使用CURL中POST方式提交數據 *@param string $xml 要提交的$xml數據 */ public function cPost($xml){ $xml = preg_replace("/[\n\t\s]+/",'',$xml);//去除其中的特殊字符、空格和換行 $digest = md5($xml.$this->key); $data_digest = strtoupper($digest); $xml = iconv('UTF-8', 'GBK',$xml); $curlPost = 'data_Isdigest=Y&logistics_interface='.$xml.'&data_digest='.$data_digest; $ch = curl_init();//初始化curl會話,返回一個句柄 curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_POST, 1);//啓用時會發送一個常規的POST請求,類型爲:application/x-www-form-urlencoded,就像表單提交的同樣 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);//將 curl_exec() 獲取的信息以文件流的形式返回,而不是直接輸出 $res = curl_exec($ch); curl_close($ch); var_dump(self::xmlToArray($res)); }