php实现soap
PHP 实现 SOAP
SOAP(Simple Object Access Protocol)是一种基于 XML 的协议,用于在 Web 服务之间交换结构化信息。PHP 提供了内置的 SoapClient 和 SoapServer 类,可以方便地实现 SOAP 客户端和服务端。
创建 SOAP 服务端
使用 SoapServer 类可以快速创建一个 SOAP 服务端。以下是一个简单的示例:
<?php
class MyService {
public function sayHello($name) {
return "Hello, " . $name;
}
}
$options = array(
'uri' => 'http://example.com/soap',
'soap_version' => SOAP_1_2
);
$server = new SoapServer(null, $options);
$server->setClass('MyService');
$server->handle();
?>
创建 SOAP 客户端
使用 SoapClient 类可以调用远程 SOAP 服务。以下是一个调用上述服务的示例:
<?php
$options = array(
'location' => 'http://example.com/soap_server.php',
'uri' => 'http://example.com/soap',
'soap_version' => SOAP_1_2
);
$client = new SoapClient(null, $options);
$response = $client->sayHello('World');
echo $response;
?>
处理 WSDL
如果服务端提供了 WSDL(Web Services Description Language)文件,客户端可以直接使用 WSDL 进行初始化:
<?php
$client = new SoapClient('http://example.com/soap_server.php?wsdl');
$response = $client->sayHello('World');
echo $response;
?>
错误处理
在 SOAP 调用过程中可能会遇到各种错误,可以通过 try-catch 块捕获 SoapFault 异常:
<?php
try {
$client = new SoapClient('http://example.com/soap_server.php?wsdl');
$response = $client->sayHello('World');
echo $response;
} catch (SoapFault $e) {
echo "Error: " . $e->getMessage();
}
?>
自定义 SOAP 头
某些情况下需要在 SOAP 请求中添加自定义头部信息:
<?php
$header = new SoapHeader(
'http://example.com/soap',
'AuthHeader',
array('username' => 'user', 'password' => 'pass')
);
$client = new SoapClient('http://example.com/soap_server.php?wsdl');
$client->__setSoapHeaders($header);
$response = $client->sayHello('World');
echo $response;
?>
调试 SOAP 请求
可以通过 getLastRequest 和 getLastResponse 方法查看最后的请求和响应内容:
<?php
$client = new SoapClient('http://example.com/soap_server.php?wsdl');
$response = $client->sayHello('World');
echo "Request:\n" . $client->__getLastRequest() . "\n";
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>
注意事项
- 确保 PHP 已启用 SOAP 扩展(php_soap.dll 或 soap.so)。
- 在开发环境中可以开启 WSDL 缓存以提高性能,但在生产环境中可能需要禁用缓存。
- 对于复杂的 SOAP 服务,建议使用专门的工具(如 SoapUI)进行测试和调试。







