dsla94915 2014-04-23 23:23
浏览 43
已采纳

在PHP中将XML响应转换为数组

I am getting xml back from an API request and want to know how to turn only the <soap:Body> to </soap:Body> section of it into an array in PHP. I haven't seen any simple or logical ways to do this in my searching.

Any information that would point me in the correct direction would be great!

Thanks in advance.

Sample XML:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Header>
    <wsa:Action>http://www.urlhere.com/</wsa:Action>
    <wsa:MessageID>urn:uuid:00000000-0000-0000-0000-000000000000</wsa:MessageID>
    <wsa:RelatesTo>urn:uuid:00000000-0000-0000-0000-000000000000</wsa:RelatesTo>
    <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
    <wsse:Security>
      <wsu:Timestamp wsu:Id="Timestamp-4cf61b60-957a-454a-a828-90bd373301af">
        <wsu:Created>2001-01-01T00:00:00Z</wsu:Created>
        <wsu:Expires>2001-01-01T00:00:00Z</wsu:Expires>
      </wsu:Timestamp>
    </wsse:Security>
  </soap:Header>
  <soap:Body>
    <blah xmlns="http://www.urlhere.com/schema">
      <blahblah>
        <blahblahblah>0</blahblahblah>
      </blahblah>
    </blah>
  </soap:Body>
</soap:Envelope>

I would like this as a result

array('body'=>array('blah'=>array('blahblah'=>array('blahblahblah'=>0))))
  • 写回答

1条回答 默认 最新

  • dow5001 2014-04-23 23:53
    关注

    If you were to use SimpleXML http://www.php.net/manual/en/book.simplexml.php

    You could craft an xpath to match on the namespaced element.

    $simple = simplexml_load_string($xml);
    $result = $simple->xpath('//soap:Body');
    echo $result[0]->blah->blahblah->blahblahblah;
    

    I'm not going to present the "array" solution as complex XML structures require different kinds of processing/iteration, all covered by the simpleXML documentation.


    Addition: Adding a better example of namespace consumption

    $simple = simplexml_load_string($xml);
    $simple->registerXPathNamespace('foo','http://www.urlhere.com/schema');
    $result = $simple->xpath('//foo:blah');
    echo $result[0]->blahblah->blahblahblah;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。