You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用SOAP服务报错HTTP 415,如何将结果转JSON在HTML页面展示

问题解决步骤

1 报错HTTP 415的原因及修复

415状态码代表服务端不支持请求携带的媒体类型,你的代码存在三个核心问题:

  • 未设置SOAP请求要求的Content-Type请求头,SOAP 1.1版本需设置为text/xml; charset=utf-8,SOAP 1.2版本需设置为application/soap+xml; charset=utf-8
  • 仅开启了CURLOPT_POST配置,未传递符合对应SOAP版本规范的XML请求体
  • 引入了nusoap库但未实际使用,同时认证参数拼接逻辑不符合常规SOAP服务的认证规则,大部分SOAP服务的认证信息需要放在XML请求体的Header节点中,而不是放在CURLOPT_USERPWD里拼接多段参数

2 修正后的完整实现代码

<?php
// 配置参数
$soapWsdlUrl = "http://192.168.26.16:8080/Licencias/wsbepsamov?wsdl"; // 替换为实际WSDL地址
$user = "test";
$password = "123456";
$documento = "34115410";
$tarjeta = "6274311750000090";
$dataFromTheForm = "2021";

// 构建SOAP请求XML(根据你实际接口的参数结构调整)
$postXml = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.yourdomain.com/">
   <soapenv:Header>
       <ws:AuthHeader>
           <username>$user</username>
           <password>$password</password>
           <documento>$documento</documento>
           <tarjeta>$tarjeta</tarjeta>
       </ws:AuthHeader>
   </soapenv:Header>
   <soapenv:Body>
      <ws:DoSomething>
         <arg0>$dataFromTheForm</arg0>
      </ws:DoSomething>
   </soapenv:Body>
</soapenv:Envelope>
XML;

// 初始化cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $soapWsdlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postXml);
// 设置请求头,解决415错误
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: text/xml; charset=utf-8',
    'Content-Length: ' . strlen($postXml)
]);
// 如果是自签名SSL可以开启下面两行
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$response = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);

if ($curlError) {
    die("请求错误:" . $curlError);
}

// 解析XML响应
$responseXml = simplexml_load_string($response);
// 提取Body节点内容,转成数组再转JSON
$soapBody = $responseXml->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
$responseData = json_decode(json_encode($soapBody), true);
$jsonResult = json_encode($responseData, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
?>

<!-- HTML页面展示JSON -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>接口响应结果</title>
    <style>
        pre {background: #f5f5f5; padding: 15px; border-radius: 5px;}
    </style>
</head>
<body>
    <h2>接口返回JSON数据:</h2>
    <pre><?php echo htmlspecialchars($jsonResult); ?></pre>
</body>
</html>

3 注意事项

  • 需将代码中XML结构的命名空间、节点名称替换为你实际调用的SOAP接口的规范结构,可以先请求WSDL地址查看完整的参数定义
  • 如果服务使用SOAP 1.2版本,将Content-Type替换为application/soap+xml; charset=utf-8即可
  • 如果你要更简单的实现,可以直接使用PHP内置的SoapClient类,不需要手动拼接XML和处理cURL请求,代码会更简洁

内容的提问来源于stack exchange,提问作者ALDO56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:36:05