如何在 PHP 中发送 xml 数据作为请求内容

新人實習生一枚- 最近在公司項目中遇需要進行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 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!