代碼片段展示了 PHP 實現 SOAP 服務的三個文件:服務類 addclass.php、服務端入口 server.php、客戶端調用 client.php,但 WSDL 內容被截斷。以下補全完整可運行示例。
AddClass.php<?php
class AddClass {
/**
* @param int $x
* @param int $y
* @return int
*/
public function add($x, $y) {
return (int)$x + (int)$y;
}
}
test.wsdl (關鍵:定義服務接口契約)<?xml version="1.0" encoding="UTF-8"?>
<definitions name="AddService"
targetNamespace="urn:AddService"
xmlns:tns="urn:AddService"
xmlns:soap="https://schemas.xmlsoap.org/wsdl/soap/"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="https://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema targetNamespace="urn:AddService">
<xsd:element name="add">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="x" type="xsd:int"/>
<xsd:element name="y" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="addResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="return" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</types>
<message name="addRequest">
<part name="parameters" element="tns:add"/>
</message>
<message name="addResponse">
<part name="parameters" element="tns:addResponse"/>
</message>
<portType name="AddPortType">
<operation name="add">
<input message="tns:addRequest"/>
<output message="tns:addResponse"/>
</operation>
</portType>
<binding name="AddBinding" type="tns:AddPortType">
<soap:binding style="document" transport="https://schemas.xmlsoap.org/soap/http"/>
<operation name="add">
<soap:operation soapAction="urn:AddService#add"/>
<input><soap:body use="literal"/></input>
<output><soap:body use="literal"/></output>
</operation>
</binding>
<service name="AddService">
<port name="AddPort" binding="tns:AddBinding">
<soap:address location="https://localhost/server.php"/>
</port>
</service>
</definitions>
server.php<?php
require_once "AddClass.php";
$server = new SoapServer("test.wsdl");
$server->setClass("AddClass");
$server->handle();
client.php<?php
try {
$client = new SoapClient("test.wsdl");
$result = $client->add(7, 8);
echo "7 + 8 = $result\n"; // 輸出 15
} catch (SoapFault $e) {
echo "SOAP Fault: " . $e->getMessage();
}
ini_set('soap.wsdl_cache_enabled', 0);。targetNamespace、service、portType、PHP 類方法名需嚴格對應。SoapFault,記錄 $e->getTraceAsString() 便於排查。<types> 中定義 complexType,PHP 類屬性需為 public 或提供 __get/__set。現代項目推薦使用 RESTful JSON API 替代 SOAP,但維護舊系統時完整 WSDL 定義是互操作基石。