首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 呼叫 WebService 完整實戰:NuSOAP 庫應用指南

     編輯:PHP 綜合知識

NuSOAP 簡介

NuSOAP 是純 PHP 實現的 SOAP 工具包,無需擴展支援,相容所有 PHP 環境。支援 SOAP 1.1、WSDL 1.1,可與 .NET、Java 等異構系統互操作。

安裝與環境

  • 下載:SourceForge 專案頁
  • 解壓後將 lib/ 目錄置於專案可存取路徑
  • 引入核心檔:require_once('lib/nusoap.php');

兩種呼叫方式

方式一:直接呼叫

<?php
require_once('lib/nusoap.php');

$client = new soapclient('https://localhost/Webservices/Service.asmx?WSDL', 'wsdl');

$params = [
    'strUsername' => 'username',
    'strPassword' => md5('password')
];

$result = $client->call('login', $params);

// 除錯資訊
// echo $client->debug_str;
?>

方式二:Proxy 代理模式(推薦)

<?php
require_once('lib/nusoap.php');

$client = new soapclient('https://localhost/Webservices/Service.asmx?WSDL', 'wsdl');
$proxy = $client->getProxy();  // 產生代理類

$result = $proxy->login('username', md5('password'));  // 如呼叫本地方法
?>

中文亂碼完整解決方案

核心問題:xml_encoding = 'utf-8' 時,NuSOAP 預設執行 utf8_decode() 導致雙重編碼。

$client->soap_defencoding = 'utf-8';
$client->xml_encoding = 'utf-8';
$client->decode_utf8 = false;  // 關鍵:關閉自動解碼

建立 Web Service 端範例

<?php
require_once('lib/nusoap.php');

function hello() {
    return 'Hello World!';
}

$server = new soap_server();
$server->register('hello');
$server->service($HTTP_RAW_POST_DATA);
?>

WSDL 模式與複雜型別

$server->configureWSDL('MyService');
$server->register('concatenate',
    ['str1' => 'xsd:string', 'str2' => 'xsd:string'],  // 輸入
    ['return' => 'xsd:string']                          // 輸出
);

除錯三大法寶

  1. $client->request / $client->response - 原始收發封包
  2. $client->debug_str - 詳細除錯追蹤
  3. Server 端設定 $debug = 1 - 回傳端除錯資訊

錯誤處理最佳實踐

$err = $client->getError();
if ($err) {
    // 記錄錯誤、回傳友善訊息
    throw new Exception('WebService 呼叫失敗: ' . $err);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved