PHP如何以POST形式發送XML數據,PHP如何接收XML文件php
準備兩個PHP文件:一個是發送數據的postXml.php,另外一個是接收數據的getXml.phphtml
發送XML: postXml.php數組
//準備XML數據 $xmlData = " <xml>ad775b217</ToUserName> <FromUserName>tWy3zC3xUgQMR5coXif5SA< /FromUserName > <CreateTime>1366181013</CreateTime> <MsgType>text</MsgType> <Content>個人測試</Content> <MsgId>5867702771251151243</MsgId> </xml>";
第一種發送方式,也是推薦的方式, 使用CURL:app
$url = 'http://cnwyt.net/xml/getXml.php'; //接收xml數據的文件 $header[] = "Content-type: text/xml"; //定義content-type爲xml,注意是數組 $ch = curl_init ($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData); $response = curl_exec($ch); if(curl_errno($ch)){ print curl_error($ch); } curl_close($ch);
第二種發送方式,使用Socket:curl
$url = 'http://cnwyt.net/xml/getXml.php'; $header[] = "Content-type: text/xml";//定義content-type爲xml $server ='http://wang.net/'; $contentLength = strlen($xml_data); $fp = fsockopen('127.0.0.1', 80); fputs($fp, "POST $url HTTP/1.0\r\n"); fputs($fp, "Host: $server\r\n"); fputs($fp, "Content-Type: text/xml\r\n"); fputs($fp, "Content-Length: $contentLength\r\n"); fputs($fp, "Connection: close\r\n"); fputs($fp, "\r\n"); // all headers sent fputs($fp, $xmlData ); $result = ''; while (!feof($fp)) { $result .= fgets($fp, 128); } var_dump($result);
接收XML: getXml.phppost
//接收數據,並將數據寫入文件中 //$xml = $HTTP_RAW_POST_DATA; $xml = $GLOBALS['HTTP_RAW_POST_DATA']; //將xml數據寫入文本文件"a.txt"中 $handle = fopen('a.txt','a+'); fwrite($handle,$xml);
問題:爲何不使用$_POST接收?測試
解答:因爲PHP默認只識別application/x-www.form-urlencoded標準的數據類型,對型如text/xml的內容沒法解析爲$_POST數組,故保留原型,交給$GLOBALS['HTTP_RAW_POST_DATA'] 來接收。注意,$HTTP_RAW_POST_DATA 對於 enctype="multipart/form-data" 表單數據不可用。url
擴展閱讀:.net
http://php.net/manual/zh/ref.curl.phpcode
使用PHP CURL的POST數據
http://www.nowamagic.net/librarys/veda/detail/124
$HTTP_RAW_POST_DATA
http://www.cnblogs.com/xwblog/archive/2011/12/23/2299672.html