繁体   English   中英

如何使用PHP从xml输出获取值

[英]How to get values from xml output using PHP

如何使用PHP从下面的结果中获取值。

<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <soapenv:Header/>
      <soapenv:Body>
        <p558:registerDonorResponse xmlns:p558="http://ws.ots.labcorp.com">
          <p558:registerDonorReturn xmlns:p118="http://data.ws.ots.labcorp.com">
            <p118:clientRegistrationId>clr1</p118:clientRegistrationId>
            <p118:labcorpRegistrationNumber>100059064</p118:labcorpRegistrationNumber>
            <p118:registrationTime>2012-12-01T05:40:51.628Z</p118:registrationTime>
          </p558:registerDonorReturn>
        </p558:registerDonorResponse>
      </soapenv:Body>
    </soapenv:Envelope>

谢谢。

您的XML包含名称空间前缀的标签,这对于SOAP响应来说很常见。

看看php的SimpleXML文档中的以下注释

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach ($child->person as $out_ns)
{
    echo $out_ns;
}

在您的情况下,访问属性的代码应如下所示(已针对so.xml文件中的XML进行了测试):

<?php
  $xml = file_get_contents('so.xml');
  $sxe = simplexml_load_string($xml);

  $ns = $sxe->getNamespaces(true);

  $child =
    $sxe->children($ns['soapenv'])->
      Body->children($ns['p558'])->
      registerDonorResponse->registerDonorReturn->children($ns['p118']);

  var_dump($child);

结果:

$ php -f so.php 
object(SimpleXMLElement)#4 (3) {
  ["clientRegistrationId"]=>
  string(4) "clr1"
  ["labcorpRegistrationNumber"]=>
  string(9) "100059064"
  ["registrationTime"]=>
  string(24) "2012-12-01T05:40:51.628Z"
}

但是请注意,手动发出SOAP请求和解析响应通常是一个坏习惯,请考虑使用SOAP客户端

你尝试了什么?

无论如何,您都可以使用PHP的simplexml_load_file或功能全面的DOMDocument class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM