用php获取xml节点

时间:2015-12-28 18:47:17

标签: php xml

我试图回应/分配一个变量到节点“code”的内容状态;

我可以获得request-id就好......

任何人的想法?

<?
$responseXML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<payment xmlns="http://www.example.com" self="http://www.example.com">
  <merchant-account-id ref="http://www.example.com">0000</merchant-account-id>
  <transaction-id>0000</transaction-id>
  <request-id>0000</request-id>
  <transaction-type>auth</transaction-type>
  <transaction-state>success</transaction-state>
  <completion-time-stamp>2015-12-28T17:39:25.000Z</completion-time-stamp>
  <statuses>
    <status code="201.0000" description="3d-acquirer:The resource was successfully created." severity="information"/>
  </statuses>
  <avs-code>P</avs-code>
  <requested-amount currency="GBP">0.01</requested-amount>
  <account-holder>
    <first-name>test</first-name>
    <last-name>test</last-name>
    <email>test.test@hotmail.co.uk</email>
    <phone>00000000000</phone>
    <address>
    <street1>test</street1>
    <city>test test</city>
    <state>test</state>
    <country>GB</country>
    </address>
  </account-holder>
  <card-token>
    <token-id>000</token-id>
    <masked-account-number>000000******0000</masked-account-number>
  </card-token>
  <ip-address>192.168.0.1</ip-address>
  <descriptor></descriptor>
  <authorization-code>000000</authorization-code>
  <api-id>000-000</api-id>
</payment>';

$doc = new DOMDocument;
$doc->loadXML($responseXML);

echo $doc->getElementsByTagName('request-id')->item(0)->nodeValue;
echo $doc->getElementsByTagName('status code')->item(0)->nodeValue;



?>

我已经尝试过simplexml looad字符串,但是用这个字母拉出头发,任何人都可以解决这个问题,在一个过程中获取这些信息的速度非常重要,所以不要强调网络服务器!

非常感谢。

3 个答案:

答案 0 :(得分:1)

使用DOM是一个好主意,但API方法有点麻烦。使用Xpath可以更轻松。

Xpath允许您使用表达式从DOM中获取节点列表或标量值:

$document = new DOMDocument;
$document->loadXML($responseXML);
$xpath = new DOMXpath($document);
$xpath->registerNamespace('example', 'http://www.example.com');

echo $xpath->evaluate('string(//example:request-id)'), "\n";
echo $xpath->evaluate('string(//example:status/@code)');

输出:

0000
201.0000

Xpath没有默认名称空间,因此如果您有XML名称空间(如您的示例),则需要为其注册前缀并使用它。

答案 1 :(得分:0)

由于code是xml标记status的属性,正在执行

getElementsByTagName('status code')

错误

有一种获取属性值getAttribute的特殊方法:

echo $doc->getElementsByTagName('status')->item(0)->getAttribute('code');

答案 2 :(得分:0)

使用XPath可以非常精确地访问status节点。

DOMDocument + XPath:

$responseXML = '...';

$doc = new DOMDocument();
$doc->loadXML($responseXML);

$xp = new DOMXpath($doc);
$xp->registerNamespace('example', 'http://www.example.com');

// Every status node.
$statusNodes = $xp->query('//example:status');
// or a very specific one.
$statusNodes = $xp->query('/example:payment/example:statuses/example:status');

$statusNode = $statusNodes[0];

$code = $statusNode->getAttribute('code');
// $code is '201.0000'.

// To change the 'code' value.
$statusNode->setAttribute('code', '302.0000');