php实现soapui
使用 PHP 实现 SoapUI 功能
PHP 可以通过内置的 SoapClient 类或第三方库(如 Guzzle)实现类似 SoapUI 的 SOAP 请求功能。以下是具体实现方法:
使用 SoapClient 发送 SOAP 请求
PHP 的 SoapClient 类可以直接与 SOAP Web 服务交互,无需手动构建 XML 请求。

$wsdl = 'http://example.com/soap-service?wsdl';
$options = [
'trace' => 1, // 启用跟踪以查看请求和响应
'exceptions' => true, // 抛出异常
'cache_wsdl' => WSDL_CACHE_NONE // 禁用 WSDL 缓存
];
try {
$client = new SoapClient($wsdl, $options);
$params = [
'param1' => 'value1',
'param2' => 'value2'
];
$response = $client->__soapCall('methodName', [$params]);
print_r($response);
// 查看原始请求和响应
echo "Request: " . $client->__getLastRequest();
echo "Response: " . $client->__getLastResponse();
} catch (SoapFault $e) {
echo "SOAP Fault: " . $e->getMessage();
}
使用 cURL 手动发送 SOAP 请求
如果需要更灵活的控制,可以使用 cURL 手动构建 SOAP 请求。
$url = 'http://example.com/soap-endpoint';
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<methodName xmlns="http://example.com/namespace">
<param1>value1</param1>
<param2>value2</param2>
</methodName>
</soapenv:Body>
</soapenv:Envelope>
XML;
$headers = [
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "http://example.com/namespace/methodName"',
'Content-Length: ' . strlen($xml)
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
使用 Guzzle 发送 SOAP 请求
Guzzle 是一个流行的 HTTP 客户端,可以用于发送 SOAP 请求。

require 'vendor/autoload.php';
$client = new \GuzzleHttp\Client();
$response = $client->post('http://example.com/soap-endpoint', [
'headers' => [
'Content-Type' => 'text/xml; charset=utf-8',
'SOAPAction' => 'http://example.com/namespace/methodName'
],
'body' => $xml // 使用上面定义的 XML
]);
echo $response->getBody();
处理 SOAP 响应
无论使用哪种方法,SOAP 响应通常是 XML 格式,可以使用 SimpleXML 或 DOMDocument 解析。
$xmlResponse = simplexml_load_string($response);
$xmlResponse->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$result = $xmlResponse->xpath('//soap:Body/child::*');
print_r($result);
调试 SOAP 请求
调试 SOAP 请求时,可以启用 SoapClient 的跟踪功能或记录 cURL/Guzzle 的请求和响应。
// SoapClient 调试
echo "Request: " . $client->__getLastRequest();
echo "Response: " . $client->__getLastResponse();
// cURL 调试
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
通过以上方法,可以在 PHP 中实现类似 SoapUI 的功能,包括发送 SOAP 请求、处理响应和调试。






