在 PHP 中,要自定義 WSDL 文件,首先需要創(chuàng)建一個 WSDL 文件并定義所需的服務(wù)和操作。以下是一個簡單的步驟來創(chuàng)建和使用自定義 WSDL 文件:
創(chuàng)建一個新的 XML 文件并將其命名為 my_service.wsdl
。然后,編輯此文件并添加以下內(nèi)容:
<?xml version="1.0" encoding="UTF-8"?><definitions name="MyService" targetNamespace="http://example.com/my_service" xmlns:tns="http://example.com/my_service" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema targetNamespace="http://example.com/my_service">
<xsd:element name="addRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="a" type="xsd:int"/>
<xsd:element name="b" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="addResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="result" type="xsd:int"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</types>
<message name="addInput">
<part name="parameters" element="tns:addRequest"/>
</message>
<message name="addOutput">
<part name="parameters" element="tns:addResponse"/>
</message>
<portType name="MyServicePortType">
<operation name="add">
<input message="tns:addInput"/>
<output message="tns:addOutput"/>
</operation>
</portType>
<binding name="MyServiceBinding" type="tns:MyServicePortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="add">
<soap:operation soapAction="http://example.com/my_service/add"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="MyServiceService">
<port name="MyServicePort" binding="tns:MyServiceBinding">
<soap:address location="http://localhost/my_service.php"/>
</port>
</service>
</definitions>
這個 WSDL 文件定義了一個名為 “MyService” 的服務(wù),該服務(wù)有一個名為 “add” 的操作,它接受兩個整數(shù)參數(shù)并返回它們的和。
創(chuàng)建一個名為 my_service.php
的 PHP 文件并添加以下內(nèi)容:
<?php
class MyService {
public function add($a, $b) {
return $a + $b;
}
}
$server = new SoapServer("my_service.wsdl");
$server->setClass("MyService");
$server->handle();
?>
這個 PHP 文件實(shí)現(xiàn)了在 WSDL 文件中定義的 “add” 操作。
運(yùn)行 PHP 內(nèi)置的 Web 服務(wù)器以提供服務(wù):
php -S localhost:8000 my_service.php
然后,可以使用 SOAP 客戶端或其他 SOAP 工具測試服務(wù)。例如,可以創(chuàng)建一個名為 client.php
的 PHP 文件并添加以下內(nèi)容:
<?php
$client = new SoapClient("http://localhost:8000/my_service.wsdl");
$result = $client->add(3, 5);
echo "Result: " . $result;
?>
運(yùn)行 client.php
文件,應(yīng)該會看到輸出 “Result: 8”,表示服務(wù)正常工作。
通過這種方式,可以創(chuàng)建和使用自定義 WSDL 文件來定義和實(shí)現(xiàn) PHP SOAP 服務(wù)。