php soap wsdl实现
PHP SOAP WSDL 实现
创建 WSDL 文件
WSDL(Web Services Description Language)是描述 Web 服务的 XML 格式文件。以下是一个简单的 WSDL 示例,定义了一个名为 HelloService 的服务,包含一个 sayHello 操作:
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="HelloService"
targetNamespace="http://example.com/hello"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://example.com/hello"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="sayHelloRequest">
<part name="name" type="xsd:string"/>
</message>
<message name="sayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>
<portType name="HelloPortType">
<operation name="sayHello">
<input message="tns:sayHelloRequest"/>
<output message="tns:sayHelloResponse"/>
</operation>
</portType>
<binding name="HelloBinding" type="tns:HelloPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="HelloService">
<port name="HelloPort" binding="tns:HelloBinding">
<soap:address location="http://example.com/hello.php"/>
</port>
</service>
</definitions>
实现 SOAP 服务端
在 PHP 中,可以使用 SoapServer 类来实现 SOAP 服务端。以下是一个简单的服务端实现:

<?php
// 指定 WSDL 文件路径(非必须,但可用于自动生成 WSDL)
$wsdl = "hello.wsdl";
// 创建 SoapServer 实例
$server = new SoapServer($wsdl);
// 添加可调用的函数或类
$server->addFunction("sayHello");
// 定义 sayHello 函数
function sayHello($name) {
return "Hello, " . $name . "!";
}
// 处理 SOAP 请求
$server->handle();
?>
创建 SOAP 客户端
使用 SoapClient 类可以轻松调用 SOAP 服务。以下是一个客户端示例:

<?php
// WSDL 文件路径或服务端 URL
$wsdl = "http://example.com/hello.php?wsdl";
// 创建 SoapClient 实例
$client = new SoapClient($wsdl);
// 调用远程方法
$response = $client->sayHello(array("name" => "World"));
// 输出响应
echo $response->greeting; // 输出: Hello, World!
?>
使用类作为服务端
可以将一个类的方法暴露为 SOAP 服务:
<?php
class HelloService {
public function sayHello($name) {
return "Hello, " . $name . "!";
}
}
$wsdl = "hello.wsdl";
$server = new SoapServer($wsdl);
$server->setClass("HelloService");
$server->handle();
?>
调试与错误处理
SOAP 调用可能会抛出异常,可以通过 try-catch 捕获:
try {
$client = new SoapClient($wsdl);
$response = $client->sayHello(array("name" => "World"));
echo $response->greeting;
} catch (SoapFault $e) {
echo "SOAP Fault: " . $e->getMessage();
}
注意事项
- WSDL 文件必须正确描述服务端的方法和参数。
- 确保 PHP 的 SOAP 扩展已启用(
extension=soap)。 - 对于复杂类型,需要在 WSDL 中定义相应的 XML Schema。
以上示例展示了如何使用 PHP 实现基于 WSDL 的 SOAP 服务端和客户端。






