Using PHP and SOAP Protocol to Implement Web Service Communication
This article explains how to use PHP's built‑in SOAP extension to create a SoapClient, invoke web service methods with simple and complex parameters, handle exceptions, and implement authentication via SoapHeader, providing complete code examples.
Web services enable cross‑platform communication, and the SOAP (Simple Object Access Protocol) protocol uses XML over HTTP to exchange data between heterogeneous systems.
In PHP, the built‑in SOAP extension provides the SoapClient class for interacting with SOAP‑based services. First ensure the extension is enabled (e.g., by calling phpinfo() ).
A basic example creates a SoapClient with the WSDL URL, sets parameters, calls a service method, and processes the response, while catching SoapFault exceptions:
<?php
$wsdl = "http://example.com/webservice?wsdl";
$client = new SoapClient($wsdl);
$param1 = "参数1";
$param2 = "参数2";
try {
$response = $client->WebServiceMethod($param1, $param2);
var_dump($response);
} catch (SoapFault $e) {
echo "出错信息:" . $e->getMessage();
}
?>Complex parameters can be passed as associative arrays. The following snippet defines a $person array with name, age, and address, sends it to the service, and handles the response similarly.
<?php
$wsdl = "http://example.com/webservice?wsdl";
$client = new SoapClient($wsdl);
$person = [
"name" => "张三",
"age" => 25,
"address" => "北京市"
];
try {
$response = $client->WebServiceMethod($person);
var_dump($response);
} catch (SoapFault $e) {
echo "出错信息:" . $e->getMessage();
}
?>For services requiring authentication, a SOAP header can be constructed with credentials and attached to the client using SoapHeader and __setSoapHeaders() . The example below shows how to build an <auth> XML block, create the header, and invoke a secured method.
<?php
$wsdl = "http://example.com/webservice?wsdl";
$client = new SoapClient($wsdl);
$username = "用户名";
$password = "密码";
$auth = "<auth><username>{$username}</username><password>{$password}</password></auth>";
$header = new SoapHeader("http://example.com", "Authentication", $auth);
$client->__setSoapHeaders($header);
try {
$response = $client->WebServiceMethod();
var_dump($response);
} catch (SoapFault $e) {
echo "出错信息:" . $e->getMessage();
}
?>In summary, implementing SOAP communication in PHP involves enabling the extension, creating a SoapClient , preparing simple or complex parameters, optionally adding authentication headers, invoking service methods, and handling responses and errors.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.