如何在 PHP 中傳送 xml 資料作為請求內容

xiaoyaoque發表於2020-07-18

新人實習生一枚- 最近在公司專案中遇需要進行soap 獲取資料
在此留個坑
以下就是傳送xml請求的兩種方法!廢話不多說直接上程式碼

//歡迎大佬指正

$xmldata = <<<EOT
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getSupportProvince xmlns="http://WebXml.com.cn/" />
  </soap:Body>
</soap:Envelope>
EOT;
$wsdl = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?WSDL';
try{
    $client = new SoapClient($wsdl);
    $result = $client->__doRequest($xmldata,$wsdl,'http://WebXml.com.cn/getSupportProvince',1,0);//傳送xml請求 __doRequest
    var_dump($result);
}catch (SoapFault $e){
    echo $e->getMessage();
}catch(Exception $e){
    echo $e->getMessage();
}

2

<?php 
$soapUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
$xmldata = <<<EOT
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getSupportProvince xmlns="http://WebXml.com.cn/" />
  </soap:Body>
</soap:Envelope>
EOT;

$headers = array(
"POST /WebServices/WeatherWebService.asmx HTTP/1.1",
"Host: www.webxml.com.cn",
"Content-Type: text/xml; charset=utf-8",
"Content-Length: ".strlen($xmldata)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $soapUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch); 
curl_close($ch);

$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);

$parser = simplexml_load_string($response2);


$xmljson= json_encode($parser);
$xmlarray=json_decode($xmljson,true);
print_r($xmlarray);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章