用 php curl 串接 SOAP API
$headers[]="Content-Type: application/soap+xml; charset=utf-8";
$data='<info><name>Your name</name><age>Your age</age></info>'; // 資料
$url = "http:/xxx/xxx.asmx"; // API URL
$string=htmlspecialchars($data); // 先編碼
// soap
$data = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<Data xmlns="zzz">
<xml>'.$string.'</xml>
</Data>
</soap12:Body>
</soap12:Envelope>';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
$soap=simplexml_load_string($response);
$Data_XmlResult = $soap->children('http://www.w3.org/2003/05/soap-envelope')
->Body->children()->Data_Response; // 解析 response 的 soap,看要取的資料在哪一層就箭頭到哪
$info=simplexml_load_string($Data_XmlResult); // 做成物件
API 的 request 跟 response 都是試了好幾次,才終於成功。
比較要注意的幾個點:
第一次接觸 soap,完全沒概念,只能一直看別人的範例和各種嘗試才終於成功
參考資料:
https://stackoverflow.com/questions/20393140/how-to-read-soap-response-xml-in-php
https://stackoverflow.com/questions/7120586/soap-request-in-php-with-curl