从PHP SOAP响应w / SimpleXML解析xml数据的最有效方法?

时间:2012-03-15 16:55:35

标签: php xml soap

我有一个XML数据集,我通过PHP通过SOAP消费。我试图解析xml中的值,以便我可以使用这些值填充到数据库中。我一直在寻找一段时间来找到最好的方法来做到这一点。以下是一些xml的示例:

<?xml version="1.0" encoding="utf-8"?>
<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:Body>
<PaymentNotification xmlns="http://apilistener.envoyservices.com">
  <payment>
    <uniqueReference>ESDEUR11039872</uniqueReference>      
    <epacsReference>74348dc0-cbf0-df11-b725-001ec9e61285</epacsReference>
    <postingDate>2010-11-15T15:19:45</postingDate>
    <bankCurrency>EUR</bankCurrency>
    <bankAmount>1.00</bankAmount>
    <appliedCurrency>EUR</appliedCurrency>
    <appliedAmount>1.00</appliedAmount>
    <countryCode>ES</countryCode>
    <bankInformation>Sean Wood</bankInformation>
  <merchantReference>ESDEUR11039872</merchantReference>
   </payment>
    </PaymentNotification>
  </soap:Body>
</soap:Envelope>

使用SimpleXMl和namespaces / xpath,我可以访问标签和其中的值。但是,我似乎能够解析值的唯一方法是遍历节点中的每个元素,检查它的名称,如果它匹配我的字符串比较,则将其分配给数组变量。我必须解析多笔付款。例如:

//all payments
foreach($data->children() as $child) {
   //one payment
   foreach($child->children() as $subChild) {

     switch($subChild->getName()) {
        case "bankCurrency":
           $newPayment['bankCurrency'] = (string)$subChild;
       break;
    case "bankPayment":
       $newPayment['bankAmount'] = (string)$subChild;
       break;
    }
  }
}

这是最好的方法吗?或者我完全错过了某个地方的其他方式?谢谢!

1 个答案:

答案 0 :(得分:0)

经过多次试验和错误,我意识到我可以以更容易的方式实际访问xml元素。在初始循环中,我可以使用$ child-&gt; bankCurrency直接访问元素。无需进入内循环并进行任何解析。我终于绕过这个PHP xml的东西。

相关问题