我正在记录来自 API 调用的错误请求/响应。为了将日志存储在数据库中,我想用 * 替换信用卡号。
请求 XML 如下所示:
<xml>
<request servicekey="service key" branchcode="branch" language="EN" postalcode="Postal Code" country="CA" email="email@example.com">
<paxes>
<pax id="1" birthdate="19790215" firstname="John" lastname="Smith" />
<pax id="2" birthdate="19800828" firstname="Jane" lastname="Smith" />
</paxes>
<plans>
<plan code="Plan Code" >
<paxes>
<pax id="1" sumins="1200.00" />
<pax id="2" sumins="1480.31" />
</paxes>
</plan>
</plans>
<payments>
<payment amount="246.24" type="VI" ccnum="4111111111111111" ccexp="0711" ccname="John Smith" />
</payments>
</request>
</xml>
从这里我只需获取支付节点和 ccnum 属性来编辑它(xml 保存为 $requestXML):
$_req = new DOMDocument();
$_req->loadXML($requestXML);
$_xpathReq = new DOMXPath($_req);
$_reqDom = $_xpathReq->query("/xml/request/payments/payment");
$_reqDom->item(0)->setAttribute('ccnum','*****');
$requestXML = $_req->saveXML();
它按预期工作,xml中的CC编号被替换为*
$responseXML 有点不同:
<string xmlns="http://tempuri.org/">
<xml>
<request servicekey="service key" branchcode="branch code" language="EN" postalcode="Postal Code" country="CA" email="email@example.com">
<paxes>
<pax id="1" birthdate="19790215" firstname="John" lastname="Smith" />
<pax id="2" birthdate="19800828" firstname="Jane" lastname="Smith" />
</paxes>
<plans>
<plan code="Plan Code">
<paxes>
<pax id="1" sumins="1200.00" />
<pax id="2" sumins="1480.31" />
</paxes>
</plan>
</plans>
<payments>
<payment amount="246.24" type="VI" ccnum="4111111111111111" ccexp="0711" ccname="John Smith" />
</payments>
</request>
<response>
<errors>
<error>Purchase Card Processing was not approved [-1]:Cancelled: null | CARD: **** | Exp: 1407 | Amount: $246.24</error>
</errors>
</response>
</xml>
</string>
和以前一样的想法,我运行了一段非常相似的 PHP 代码:
$_req = new DOMDocument();
$_req->loadXML($responseXML);
$_xpathReq = new DOMXPath($_req);
$_reqDom = $_xpathReq->query("/string/xml/request/payments/payment");
$_reqDom->item(0)->setAttribute('ccnum','*****');
$responseXML = $_req->saveXML();
但是当我运行它时,我得到Fatal error: Call to a member function setAttribute() on a non-object
指向包含的行$_reqDom->item(0)->setAttribute('ccnum','*****');
两个 xml 之间的唯一区别是一个包含在字符串节点中,并且有一个额外的节点表示响应。我想我可以做一个解决方法(只需拉出响应节点并将其附加到请求 xml),但我现在正处于让这种方式工作是我的使命的地步。