本文目录导读:

在 PHP 中操作 WebService 主要有两种常见方式:SOAP 和 REST,由于大多数现代 WebService 是基于 REST 的(返回 JSON/XML),但老一些或企业级系统(如 SAP、银行接口)仍常用 SOAP。
下面分两种情况详细说明:
操作 REST 风格的 WebService(最常用)
REST 通常返回 JSON 格式数据,使用 curl 或 file_get_contents 即可完成。
方法1:使用 cURL(推荐,支持 GET/POST/PUT/DELETE)
<?php
function callRestAPI($url, $method = 'GET', $data = null, $headers = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// 设置请求方法
switch (strtoupper($method)) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers[] = 'Content-Type: application/json';
}
break;
case 'PUT':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers[] = 'Content-Type: application/json';
}
break;
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: // GET
if ($data) {
$url = $url . '?' . http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $url);
}
}
// 设置请求头(API Key、Token)
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 返回解析后的结果
return [
'http_code' => $httpCode,
'data' => json_decode($response, true) // 转为数组
];
}
// 示例:调用 GET 接口
$result = callRestAPI('https://api.example.com/users?page=1');
print_r($result['data']);
// 示例:调用 POST 接口(提交 JSON)
$postData = ['name' => '张三', 'email' => 'zhangsan@example.com'];
$result = callRestAPI('https://api.example.com/users', 'POST', $postData, [
'Authorization: Bearer your_token_here'
]);
print_r($result['data']);
方法2:使用 file_get_contents(仅适用于 GET,简单场景)
<?php
$url = 'https://api.example.com/users?page=1';
$options = [
'http' => [
'method' => 'GET',
'header' => "Content-Type: application/json\r\n" .
"Authorization: Bearer your_token\r\n"
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true); // 转为关联数组
print_r($data);
注意:
file_get_contents不支持 POST/PUT/DELETE,调试较困难,建议用 cURL。
方法3:使用 Guzzle(第三方库,适合复杂项目)
安装:composer require guzzlehttp/guzzle
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://api.example.com',
'timeout' => 10,
]);
// GET 请求
$response = $client->get('/users', [
'query' => ['page' => 1]
]);
// POST 请求(JSON)
$response = $client->post('/users', [
'json' => ['name' => '李四'],
'headers' => ['Authorization' => 'Bearer your_token']
]);
$body = $response->getBody()->getContents();
$data = json_decode($body, true);
操作 SOAP 风格的 WebService(老式/企业场景)
SOAP 使用 XML 格式传输,PHP 内置了 SoapClient 类。
方法1:使用 PHP 原生 SoapClient(最简单)
假设 WSDL 地址为:http://example.com/service?wsdl
<?php
try {
// 创建 SoapClient 对象
$client = new SoapClient('http://example.com/service?wsdl', [
'trace' => true, // 开启调试(可查看请求/响应XML)
'exceptions' => true,
'cache_wsdl' => WSDL_CACHE_NONE // 开发环境建议关闭缓存
]);
// 调用远程方法(方法名和参数需查看 WSDL 文档)
$result = $client->getUserInfo([
'userId' => 123,
'token' => 'abc'
]);
// 输出结果(可能是对象或数组)
print_r($result);
// 查看请求和响应(调试用)
// echo $client->__getLastRequest();
// echo $client->__getLastResponse();
} catch (SoapFault $e) {
echo "SOAP Error: " . $e->getMessage();
}
方法2:无 WSDL 时手动构造 SOAP 请求
如果服务商只提供 SOAP 端点但没有 WSDL(少见),可以手动构造 XML:
<?php
$xml = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:GetUserInfo>
<tem:userId>123</tem:userId>
</tem:GetUserInfo>
</soapenv:Body>
</soapenv:Envelope>
XML;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/service.asmx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: "http://tempuri.org/GetUserInfo"' // 常见但非必需
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
$response = curl_exec($ch);
curl_close($ch);
// 从 XML 中提取数据(使用 SimpleXML 或 DOMDocument)
$parsed = simplexml_load_string($response);
// 然后根据命名空间解析
常见问题与调试技巧
- 查看 WSDL 文档:用浏览器打开
?wsdl地址,或用工具(如 SoapUI)分析提供的接口。 - SOAP 错误:开启
exceptions并用try-catch捕获SoapFault。 - SSL 证书问题:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 仅开发环境使用 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- 调试 REST:使用 Postman 测试接口,再将参数复制到 PHP 代码。
- 调试 SOAP:开启
trace => true后调用$client->__getLastRequest()和__getLastResponse()查看原始 XML。
总结选择建议
| 场景 | 推荐方案 |
|---|---|
| 现代 API(REST + JSON) | cURL 或 Guzzle |
| 老系统(SOAP + XML) | SoapClient 原生类 |
| 简单 GET 请求 | file_get_contents |
| 需要异步/批量请求 | Guzzle(支持异步) |
| 企业级复杂 SOAP(有认证) | SoapClient + 自定义 Stream Context |
如果你能提供具体的 WebService 类型(REST 或 SOAP)和接口文档,我可以给出更精确的代码示例。