Using PHP and SOAP Protocol for Web Service Communication

This article explains how to use PHP’s built‑in SOAP extension to create a client, send simple and complex parameters, handle authentication via SoapHeader, and process responses and errors when communicating with web services.

php Courses
php Courses
php Courses
Using PHP and SOAP Protocol for Web Service Communication

Web services enable cross‑platform communication, and the SOAP protocol provides an XML‑based method for such interactions.

Using PHP’s built‑in SOAP extension, developers can create a SoapClient object, verify the extension with phpinfo(), and call remote methods.

<?php
$wsdl = "http://example.com/webservice?wsdl"; // WSDL URL
$client = new SoapClient($wsdl);
$param1 = "参数1";
$param2 = "参数2";
try {
    $response = $client->WebServiceMethod($param1, $param2);
    var_dump($response);
} catch (SoapFault $e) {
    echo "出错信息:" . $e->getMessage();
}
?>

The client can also send complex parameters such as associative arrays, and handle the returned results.

<?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 that require authentication, a SoapHeader containing username and password can be attached to the client.

<?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 with PHP involves creating a client, preparing parameters (including complex structures and authentication headers), invoking service methods, and handling responses and exceptions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPAPIWeb servicesSOAP
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.