開發者端:發送請求,並接收結果php
<?php // 下面的demo,實現的功能以下: // 1-開發者須要判斷一個用戶是否存在,去請求第三方接口。 // 2-與第三方接口的通訊,是以xml格式傳送數據。開發者把用戶信息以xml格式發送給第三方接口 // 3-第三方接口獲取開發者的xml數據,經過數據的查詢,把結果再以xml的格式發送給開發者。 //首先檢測是否支持curl if (!extension_loaded("curl")) { trigger_error("對不起,請開啓curl功能模塊!", E_USER_ERROR); } //構造xml $xmldata="<?xml version='1.0' encoding='UTF-8'?><group><name>張三</name><age>22</age></group>"; //初始一個curl會話 $curl = curl_init(); //設置url curl_setopt($curl, CURLOPT_URL,"http://localhost/demo/dealxml.php"); //設置發送方式:post curl_setopt($curl, CURLOPT_POST, true); //設置發送數據 curl_setopt($curl, CURLOPT_POSTFIELDS, $xmldata); //TRUE 將curl_exec()獲取的信息以字符串返回,而不是直接輸出 curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //執行cURL會話 ( 返回的數據爲xml ) $return_xml = curl_exec($curl); //關閉cURL資源,而且釋放系統資源 curl_close($curl); //echo $return_xml; //exit; //禁止引用外部xml實體 libxml_disable_entity_loader(true); //先把xml轉換爲simplexml對象,再把simplexml對象轉換成 json,再將 json 轉換成數組。 $value_array = json_decode(json_encode(simplexml_load_string($return_xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); echo "<pre>"; print_r($value_array); ?>
第三方接口端:接收請求,並返回處理結果json
<?php //接收傳送的數據 $fileContent = file_get_contents("php://input"); ### 把xml轉換爲數組 //禁止引用外部xml實體 libxml_disable_entity_loader(true); //先把xml轉換爲simplexml對象,再把simplexml對象轉換成 json,再將 json 轉換成數組。 $value_array = json_decode(json_encode(simplexml_load_string($fileContent, 'SimpleXMLElement', LIBXML_NOCDATA)), true); ### 獲取值,進行業務處理 $name = $value_array['name']; $age = $value_array['age']; // 經過查詢,判斷該用戶是否存在 ### 把查詢結果添加到數組中 $value_array['result'] = 1; ### 把數組轉換爲xml格式,返回 $xml = "<?xml version='1.0' encoding='UTF-8'?><group>"; foreach ($value_array as $key=>$val) { if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; }else{ $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; } } $xml.="</group>";
// echo $xml;return $xml; ?>