SOAP-ERROR: Encoding: object has no 'id' property呼叫建立印章服務時拋出錯誤,但 API 文檔聲稱 id 非必填。
<xs:element name="id" type="xs:long"/> 無 minOccurs="0",預設 minOccurs=1(必填)。ext/soap/php_encoding.c 中的 model_to_xml_object 函式,發現當 model->min_occurs == 0 才允許略過,否則拋出「object has no 'xxx' property」。在 SOAP 客戶端請求物件中補上任意 id 值(如 0 或 time()),滿足 Schema 驗證:
$params = [
'seal' => [
'id' => 0, // 必填欄位補預設值
'name' => 'MySeal',
// ...其他欄位
]
];
$client->createSeal($params);
教訓:WSDL 即契約,minOccurs 預設為 1,文檔若與 Schema 不符,以 Schema 為準。
looks like we got no XML document抓包發現回應為 multipart/related 格式(MTOM 附件封裝),非純 XML,導致 PHP SOAP 解析失敗:
HTTP/1.1 200 OK Content-Type: multipart/related; type="application/xop+xml"; boundary="uuid:..." --uuid:... Content-Type: application/xop+xml; charset=UTF-8; type="text/xml" <soap:Envelope>...</soap:Envelope> --uuid:...--
CXF 伺服端啟用 mtom-enabled=true,PHP 內建 SOAP 擴展 不支援 MTOM 解析。
| 方案 | 優點 | 缺點 | 推薦度 |
|---|---|---|---|
| 要求對方關閉 MTOM | 零代碼變更 | 需協調對方、可能違反架構規範 | ⭐⭐ |
| 改用 WSO2 WSF/PHP 擴展 | 完整支援 MTOM/WS-Security | 編譯安裝複雜、維護成本高 | ⭐⭐⭐ |
| 繼承 SoapClient 重寫 __doRequest(本文採用) | 無額外依賴、部署簡單、可控性強 | 需手動剖析 MIME 邊界、僅適用簡單場景 | ⭐⭐⭐⭐⭐ |
ZSoapClientclass ZSoapClient extends SoapClient {
public function __doRequest($request, $location, $action, $version, $one_way = 0) {
$response = parent::__doRequest($request, $location, $action, $version, $one_way);
// 1. 若回應已為純 XML 直接返回
if (strpos($response, '<?xml') === 0 || strpos($response, '<soap:') === 0) {
return $response;
}
// 2. 解析 MIME multipart/related,提取 SOAP 部分
$start = strpos($response, '<soap:Envelope');
if ($start === false) $start = strpos($response, '<soap:Body');
if ($start === false) $start = strpos($response, '<?xml');
$end = strrpos($response, '</soap:Envelope>');
if ($end === false) $end = strrpos($response, '</soap:Body>');
if ($end === false) $end = strlen($response) - 1;
return substr($response, $start, $end - $start + strlen('</soap:Envelope>'));
}
}
// 使用
$client = new ZSoapClient($wsdl, ['trace' => 1, 'exceptions' => 1]);
$result = $client->createSeal($params);
protected function extractSoapXml($raw) {
// 移除 HTTP 標頭(若包含)
$headerEnd = strpos($raw, "\r\n\r\n");
if ($headerEnd !== false) $raw = substr($raw, $headerEnd + 4);
// 嘗試直接匹配 SOAP Envelope
if (preg_match('/(<\?xml[^>]*>)?\s*(<soap:Envelope[^>]*>.*?<\/soap:Envelope>)/s', $raw, $m)) {
return $m[0];
}
// 解析 multipart boundary
if (preg_match('/boundary="([^"]+)"/', $raw, $m)) {
$boundary = '--' . $m[1];
$parts = explode($boundary, $raw);
foreach ($parts as $part) {
if (strpos($part, '<soap:Envelope') !== false || strpos($part, '<?xml') !== false) {
return trim($part);
}
}
}
return $raw; // 兜底
}
ini_set('soap.wsdl_cache_enabled', 1); 避免重複下載 WSDL。'trace' => 1,失敗時用 $client->__getLastRequest() / __getLastResponse() 除錯。PHP 呼叫 Java WebService 的核心難點在於 WSDL 契約不符 與 MTOM 附件解析。透過補齊必填欄位、繼承 SoapClient 剝離 MIME 封裝,即可在不升級基礎設施前提下穩定對接。若長期維護,建議推動服務端遷移至 REST/JSON 或 gRPC,徹底擺脫 SOAP 歷史包袱。