如何解析PHP cURL获取的SOAP WebService响应以提取字段存数据库
PHP cURL获取SOAP响应的字段提取与入库方案
你当前看到的拼接纯文本是浏览器渲染XML时过滤掉标签的效果,实际cURL拿到的$response是完整带结构的XML报文,可通过PHP内置XML解析组件精准拆分字段值,无需手动切割字符串。
改造核心逻辑
在现有cURL请求代码的基础上,将原本直接输出$response的逻辑替换为解析流程,完整可运行代码片段如下:
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://xxxxxx/WSAutorizaciones/WSAutorizacionLaboratorio.asmx?WSDL", CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <AuthenticationHeader xmlns="https://arssenasa.gob.do/"> <Cedula>001-0946651-5</Cedula> <Password>xxxxxxx</Password> <Proveedo>12077</Proveedo> </AuthenticationHeader> </soap:Header> <soap:Body> <ConsultarAfiliado xmlns="https://arssenasa.gob.do/"> <TipoDocumento>2</TipoDocumento> <NumDocumento>021827151</NumDocumento> </ConsultarAfiliado> </soap:Body> </soap:Envelope>', CURLOPT_HTTPHEADER => array("content-type: text/xml"), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:". $err; } else { // 安全配置:禁用外部实体加载,防范XXE注入风险 libxml_disable_entity_loader(true); // 加载响应XML为可操作对象 $soapXml = simplexml_load_string($response); // 注册SOAP信封命名空间 $soapXml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/'); // 注册业务接口对应的目标命名空间 $businessNs = 'https://arssenasa.gob.do/'; $soapXml->registerXPathNamespace('ns', $businessNs); // 定位到业务结果节点 $resultNodeList = $soapXml->xpath('//soap:Body/ns:ConsultarAfiliadoResponse/ns:ConsultarAfiliadoResult'); if (empty($resultNodeList)) { echo "未获取到业务返回结果"; exit; } $resultNode = $resultNodeList[0]; // 结构化提取所有字段值,自动兼容空节点 $afiliadoRecord = [ 'contrato' => (string)$resultNode->Contrato, 'cedula' => (string)$resultNode->Cedula, 'nss' => (string)$resultNode->Nss, 'nombres' => (string)$resultNode->Nombres, 'apellidos' => (string)$resultNode->Apellidos, 'id_estado' => (string)$resultNode->IdEstado, 'codigo_familiar' => (string)$resultNode->CodigoFamiliar, 'regimen' => (string)$resultNode->Regimen, // 可将返回的日期格式转换为数据库兼容格式后入库 'fecha_nacimiento' => date('Y-m-d', strtotime((string)$resultNode->FechaNacimiento)), 'edad' => (int)$resultNode->Edad, 'sexo' => (string)$resultNode->Sexo, 'tipo_documento' => (string)$resultNode->TipoDocumento, 'codigo_afiliado' => (string)$resultNode->CodigoAfiliado, 'mensaje_afiliado' => (string)$resultNode->MensajeAfiliado, ]; // $afiliadoRecord 为结构化数组,可直接通过参数绑定的方式拼接SQL写入数据库 print_r($afiliadoRecord); }
注意事项
- 不要使用正则表达式解析XML结构,一旦接口返回的节点顺序调整、内容包含特殊字符,正则匹配会直接失效
- 处理带
xsi:nil="true"标记的空节点时,强转字符串类型会自动返回空值,无需额外做节点存在性判断 - 入库前建议对提取到的字段值做长度校验,避免超过数据库字段定义的长度阈值
- 该实现完全依赖PHP内置组件,无额外扩展安装要求
内容的提问来源于stack exchange,提问作者Diasline
相关产品推荐
相关产品推荐

