json解码获取属性

时间:2014-09-27 14:05:21

标签: php xml json

我似乎无法在网上找到答案,但我认为这是因为我不太清楚要搜索什么,因为我对xml很新。 JSON。

如果我有这个xml

$postData = '<PaymentNotification Stage="false">
  <MerchantReference>100004117</MerchantReference>
  <TransactionType>PAYMENT</TransactionType>
  <TransactionState>SUCCESSFUL</TransactionState>
  <ResultCode>00</ResultCode>
  <ResultMessage>Successful</ResultMessage>
  <PayUReference>1167986976014</PayUReference>
  <Basket>
    <Description>Store Order Number:100004117</Description>
    <AmountInCents>100</AmountInCents>
    <CurrencyCode>ZAR</CurrencyCode>
    <Products/>
  </Basket>
  <PaymentMethodsUsed>
    <Eft BankName="ABSA" AmountInCents="100" Reference="CUMVSIUPFG" AccountNumber="4077920871" BranchNumber="632005" AccountType="Cheque" TimeLimit="168" Currency="ZAR"/>
  </PaymentMethodsUsed>
  <IpnExtraInfo>
    <ResponseHash></ResponseHash>
  </IpnExtraInfo>
</PaymentNotification>';

然后json解码它

$returnData = json_decode(json_encode(simplexml_load_string($postData)),true);

我可以检索对象,例如。

$cost_amount = $returnData['Basket']['AmountInCents'];

但是如何获得Eft中的属性,例如。 BANKNAME?

我试过这些但没有成功

$paid_amount = $returnData['PaymentMethodsUsed']['CreditCard']['@AmountInCents'];
and
$paid_amount = $returnData[0]->PaymentMethodsUsed[0]->CreditCard->AmountInCents;

2 个答案:

答案 0 :(得分:0)

对于这种情况,为什么不正常遍历节点,并使用->attributes()方法:

$postData = '<PaymentNotification Stage="false">
  <MerchantReference>100004117</MerchantReference>
  <TransactionType>PAYMENT</TransactionType>
  <TransactionState>SUCCESSFUL</TransactionState>
  <ResultCode>00</ResultCode>
  <ResultMessage>Successful</ResultMessage>
  <PayUReference>1167986976014</PayUReference>
  <Basket>
    <Description>Store Order Number:100004117</Description>
    <AmountInCents>100</AmountInCents>
    <CurrencyCode>ZAR</CurrencyCode>
    <Products/>
  </Basket>
  <PaymentMethodsUsed>
    <Eft BankName="ABSA" AmountInCents="100" Reference="CUMVSIUPFG" AccountNumber="4077920871" BranchNumber="632005" AccountType="Cheque" TimeLimit="168" Currency="ZAR"/>
  </PaymentMethodsUsed>
  <IpnExtraInfo>
    <ResponseHash></ResponseHash>
  </IpnExtraInfo>
</PaymentNotification>';

$xml = simplexml_load_string($postData);

$cents = (string) $xml->PaymentMethodsUsed->Eft->attributes()->AmountInCents;
echo $cents; // 100

答案 1 :(得分:-1)

很高兴解决这个问题。完全使用了命中和试用方法。 我的方法: 我试图通过以下方式对PaymentMethodUsed数组进行json_encode编码:

 $x = $returnData['PaymentMethodsUsed'];
 echo json_encode($x);

结果是:

{"Eft":{"@attributes":{"BankName":"ABSA","AmountInCents":"100","Reference":"CUMVSIUPFG","AccountNumber":"4077920871","BranchNumber":"632005","AccountType":"Cheque","TimeLimit":"168","Currency":"ZAR"}}}

所以,猜测了这种方法,我希望你可以使用以下方法获得所需的价值:

echo $returnData['PaymentMethodsUsed']['Eft']['@attributes']['BankName'];