php編程中經常會用到用xml格式傳送數據,如調用微信等第三方接口經常用到,這里演示下php以curl形式發送xml,並通過服務器接收
一、發送xml數據 —— postXml.php
<?php
// 首先檢測是否支持curl
if (!extension_loaded("curl")) {
trigger_error("對不起,請開啟curl功能模塊!", E_USER_ERROR);
}
// 構造xml數據
$xmlData = "
<xml>
<AppId>wxf8b4f85f3a794e77</AppId>
<ErrorType>1001</ErrorType>
<Description>錯誤描述</Description>
<AlarmContent>transaction_id=33534453534</AlarmContent>
<TimeStamp>1393860740</TimeStamp>
<AppSignature>f8164781a303f4d5a944a2dfc68411a8c7e4fbea</AppSignature>
<SignMethod>sha1</SignMethod>
</xml>";
$url = 'http://web.whm.com/getXml.php'; //接收xml數據的文件
$ch = curl_init(); // 初始一個curl會話
$timeout = 30; // php運行超時時間,單位秒
curl_setopt($ch, CURLOPT_URL, $url); // 設置url
curl_setopt($ch, CURLOPT_POST, 1); // post 請求
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:text/xml; charset=utf-8")); // 一定要定義content-type為xml,要不然默認是text/html!
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);//post提交的數據包
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // PHP腳本在成功連接服務器前等待多久,單位秒
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch); // 抓取URL並把它傳遞給瀏覽器
// 是否報錯
if(curl_errno($ch))
{
print curl_error($ch);
}
curl_close($ch); // //關閉cURL資源,並且釋放系統資源
echo $result;

二、接收xml數據——getXml.php
<?php
//接收傳送的數據
$xml = file_get_contents("php://input");
//將xml數據寫入文本文件"whm.txt"中
$handle =fopen('whm.txt','w');
fwrite($handle,$xml);

三、注意事項
- 構造xml時一定要注意格式正確,不能有空格等
- 一定要定義content-type為xml,要不然默認是text/html
轉載請標明原文鏈接: https://www.jianshu.com/p/7b86546f5300
更多精彩請訪問個人博客:https://www.whmblog.cn/
</div>