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

PHP从SOAP响应字符串中提取balance值的问题求助

从SOAP响应中提取balance字段的正确方法

问题场景

通过PHP CURL获取到SOAP格式响应后,尝试用simplexml_load_string结合XPath提取balance字段值失败,以下是相关内容:

SOAP响应内容

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:getActiveBonusAccountsResponse xmlns:ns2="http://processing.cards.crystals.ru/">
<return>
<balance>26</balance>
<bonusAccountId>72055</bonusAccountId>
<bonusAccountsTypeVO>
<accountsType>MONEY</accountsType>
<bonusAccountTypeCode>4211</bonusAccountTypeCode>
<bonusAccountTypeId>4211</bonusAccountTypeId>
<bonusAccountsTypeName>Основной</bonusAccountsTypeName>
<bonusCourse>100</bonusCourse>
<currencyCourse>100</currencyCourse>
<entirePurchase>true</entirePurchase>
<writeOffAllAmountAtOnce>false</writeOffAllAmountAtOnce>
</bonusAccountsTypeVO>
<enabled>true</enabled>
</return>
</ns2:getActiveBonusAccountsResponse>
</soap:Body>
</soap:Envelope>

尝试的错误代码

$soap = simplexml_load_string($soap_response);
$soap->registerXPathNamespace('ns2', 'http://processing.cards.crystals.ru/');
$test = (string) $soap->xpath('//ns2:return/ns2:balance[1]')[0];
var_dump($test);

问题原因

原XPath错误地给return和balance节点加上了ns2前缀,但这两个节点并不属于ns2命名空间,只有外层的getActiveBonusAccountsResponse节点才在ns2命名空间下,导致XPath无法匹配到目标节点。

正确解决方案

方案1:修正XPath写法

调整XPath路径,仅对属于ns2命名空间的节点使用前缀:

$soap = simplexml_load_string($soap_response);
$soap->registerXPathNamespace('ns2', 'http://processing.cards.crystals.ru/');

// 定位到ns2命名空间下的响应节点,再获取其子节点
$balanceNodes = $soap->xpath('//ns2:getActiveBonusAccountsResponse/return/balance');
if (!empty($balanceNodes)) {
    $balance = (string) $balanceNodes[0];
    var_dump($balance); // 输出 string(2) "26"
} else {
    var_dump('未找到balance字段');
}

方案2:直接遍历SimpleXML节点层级

无需使用XPath,通过节点层级直接访问目标字段:

$soap = simplexml_load_string($soap_response);

// 逐层访问命名空间节点和子节点
$soapBody = $soap->children('soap', true)->Body;
$responseNode = $soapBody->children('ns2', true)->getActiveBonusAccountsResponse;
$balance = (string) $responseNode->return->balance;

var_dump($balance); // 输出 string(2) "26"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:27:33