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

PHP中如何将CURL返回的XML响应转换为JSON或数组?

解决PHP中XML响应转数组/JSON的问题

问题核心

返回的XML响应开头多了一个无效的0前缀,这是导致XML解析失败的关键原因,必须先清理该字符再进行格式转换。

解决方案

1. 清理响应内容

使用正则替换移除XML标签前的所有无效字符(兼容开头非固定0的情况):

$cleanResponse = preg_replace('/^[^<]+/', '', $response);

如果确定开头只有单个0,也可以直接截取:

$cleanResponse = substr($response, 1);

2. XML转数组/JSON

利用PHP内置的SimpleXMLElement结合JSON转换函数实现格式转换:

// 解析清理后的XML,保留CDATA内容
$xml = simplexml_load_string($cleanResponse, "SimpleXMLElement", LIBXML_NOCDATA);
// 转成数组
$responseArray = json_decode(json_encode($xml), true);
// 转成JSON字符串
$responseJson = json_encode($xml);

完整修改后的代码

将清理和解析逻辑整合到原CURL代码中:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => '',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>"<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='' xmlns:xsd='' xmlns:ns2='' xmlns:ser='http://service/'>
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
        <ser:NCAtomaticaDTE>
            <arg0>
                <![CDATA[
                    <mensaje/>
                        <nca-requerimiento>
                            <programa>
                                <version>Version VER6207I 23/01/2012 09:30</version>
                                <timeout>11</timeout>
                            </programa>
                            <datos-originales>
                                <fecha>$fecha_compra_boleta_formateada</fecha>
                                <sucursal>$sucursal_boleta</sucursal>
                                <terminal>$numero_terminal_boleta</terminal>
                                <numero-boleta>$numero_folio_boleta</numero-boleta>
                                <folio></folio>
                                <rmc></rmc>
                            </datos-originales>
                        </nca-requerimiento>
                    </mensaje>
                ]]>
            </arg0>
        </ser:NCAtomaticaDTE>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>",
  CURLOPT_HTTPHEADER => array(
    'SOAPaction: kkkk',
    'Content-Type: application/xml'
  ),
));

$response = curl_exec($curl);
curl_close($curl);

// 清理响应中的无效前缀
$cleanResponse = preg_replace('/^[^<]+/', '', $response);

// 解析XML并转换格式
$xml = simplexml_load_string($cleanResponse, "SimpleXMLElement", LIBXML_NOCDATA);
$responseArray = json_decode(json_encode($xml), true);

// 输出数组结果
print_r($responseArray);
// 如需JSON格式,替换为 echo json_encode($responseArray);

注意事项

  • LIBXML_NOCDATA参数确保XML中的CDATA块内容被正确解析,不会丢失数据
  • 转换后的数组可以直接通过键名访问数据,例如$responseArray['nca-respuesta']['codigo-Error']获取错误码
  • 若解析仍报错,可通过libxml_get_errors()查看具体XML语法错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:15:06