用PHP读取XML

时间:2010-04-30 16:04:50

标签: php xml simplexml

我正在尝试检查从外部返回的某些XML中的字段。 XML在变量调用$out中返回,当您查看页面源时,您将获得以下XML输出,

<?xml version="1.0" encoding="UTF-8"?>
<ResponseBlock Live="FALSE" Version="3.51">
  <Response Type="AUTH">
    <OperationResponse>
      <TransactionReference>23-9-1334895</TransactionReference>
      <TransactionCompletedTimestamp>2010-04-30 15:59:05</TransactionCompletedTimestamp>
      <AuthCode>AUTH CODE:TEST</AuthCode>

      <TransactionVerifier>AlaUOS1MOnN/iwc5s2WPDm5ggrCLwesUnHs9h+W0N3CRaln2W6lh+6dtaRFFhLdwfnw6y7lRemyJUYl9a3dpWfzORE6DaZkFMb+dIb0Ne1UxjFEJkrEtjzx/i8KSayrIBrT/yGZOoOT42EZ9loc+UkdGk/pqYvj8bZztvgBNo2Ak=</TransactionVerifier>
      <Result>1</Result>
      <SettleStatus>0</SettleStatus>
      <SecurityResponseSecurityCode>1</SecurityResponseSecurityCode>
      <SecurityResponsePostCode>1</SecurityResponsePostCode>
      <SecurityResponseAddress>1</SecurityResponseAddress>

    </OperationResponse>
    <Order>
      <OrderInformation>This is a test order</OrderInformation>
      <OrderReference>Order0001</OrderReference>
    </Order>
  </Response>
</ResponseBlock>

我想检查“结果”字段中的值。我不确定如何使用PHP访问信息,到目前为止,我已经

$xml = simplexml_load_string($out);

非常感谢

2 个答案:

答案 0 :(得分:3)

使用它应该就够了:

echo $xml->Response->OperationResponse->Result;

此处显示:

1


SimpleXML将XML数据加载到由数组和对象组成的结构中 - 这使得访问变得容易。

要了解此结构的外观,您可以使用:

var_dump($xml);


哪个会给你,这里:

object(SimpleXMLElement)[1]
  public '@attributes' => 
    array
      'Live' => string 'FALSE' (length=5)
      'Version' => string '3.51' (length=4)
  public 'Response' => 
    object(SimpleXMLElement)[2]
      public '@attributes' => 
        array
          'Type' => string 'AUTH' (length=4)
      public 'OperationResponse' => 
        object(SimpleXMLElement)[3]
          public 'TransactionReference' => string '23-9-1334895' (length=12)
          public 'TransactionCompletedTimestamp' => string '2010-04-30 15:59:05' (length=19)
          public 'AuthCode' => string 'AUTH CODE:TEST' (length=14)
          public 'TransactionVerifier' => string 'AlaUOS1MOnN/iwc5s2WPDm5ggrCLwesUnHs9h+W0N3CRaln2W6lh+6dtaRFFhLdwfnw6y7lRemyJUYl9a3dpWfzORE6DaZkFMb+dIb0Ne1UxjFEJkrEtjzx/i8KSayrIBrT/yGZOoOT42EZ9loc+UkdGk/pqYvj8bZztvgBNo2Ak=' (length=173)
          public 'Result' => string '1' (length=1)
          public 'SettleStatus' => string '0' (length=1)
          public 'SecurityResponseSecurityCode' => string '1' (length=1)
          public 'SecurityResponsePostCode' => string '1' (length=1)
          public 'SecurityResponseAddress' => string '1' (length=1)
      public 'Order' => 
        object(SimpleXMLElement)[4]
          public 'OrderInformation' => string 'This is a test order' (length=20)
          public 'OrderReference' => string 'Order0001' (length=9)


知道结构,达到你感兴趣的元素应该很容易; - )

答案 1 :(得分:0)

您可以使用xpath查询执行此操作:

$xml->xpath('/ResponseBlock/Response/OperationResponse/Result');

应该给你你想要的东西。

http://www.php.net/manual/en/simplexmlelement.xpath.php