dqy13020940 2016-06-10 12:36
浏览 109
已采纳

使用simplexml_load_string的XML到数组

I need to convert XML to array,but its not converting

here is my code

<?php
$response='<?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body>
<Search xmlns="http:url">
  <Request>
    <aaa>string</aaa>
    <bbb>string</bbb>
    <ccc>srting</ccc>
    <SourceName>string</SourceName>

  </Request>
</Search>
</soap:Body>
</soap:Envelope>';


function xml2Array($xmlstring)
{
    $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    return json_decode($json,TRUE);
}
$arr = xml2Array($response);
print_r($arr); 

But if i remove

<soap:Body> 

from the XML it works fine, What is the issue how to resole it

  • 写回答

1条回答 默认 最新

  • dsg435665475 2016-06-10 12:57
    关注

    Try something similar to solution from this question.

    In your case try this code

    <?php
    $response='<?xml version="1.0" encoding="utf-8"?>
     <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    
    <soap:Body>
    <Search xmlns="http:url">
      <Request>
        <aaa>string</aaa>
        <bbb>string</bbb>
        <ccc>srting</ccc>
        <SourceName>string</SourceName>
    
      </Request>
    </Search>
    </soap:Body>
    </soap:Envelope>';
    
    
    function xml2Array($xmlstring)
    {
        $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA, "http://schemas.xmlsoap.org/soap/envelope/");
        $xml->registerXPathNamespace('soap-env', 'http://schemas.xmlsoap.org/soap/envelope/');
        $bodies = $xml->xpath('//soap-env:Body');
        if (is_array($bodies) && !empty($bodies[0])) {
            $json = json_encode($bodies[0]);
            return json_decode($json,TRUE);
        } else {
            return false;
        }
    }
    $arr = xml2Array($response);
    print_r($arr);
    

    And output will be:

    Array
    (
        [Search] => Array
            (
                [Request] => Array
                    (
                        [aaa] => string
                        [bbb] => string
                        [ccc] => srting
                        [SourceName] => string
                    )
    
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python使用pulp线性优化时报错
  • ¥15 开源或低价数据中台哪个最好
  • ¥15 arduino编程出现字符串疑似覆盖现象
  • ¥15 我的b站在没有碰到屏幕的情况下偶尔会自动跳出进度条,就像在屏幕上点了一下一样,但我并没有点。而且视频进度并没有变。这可能是什么原因造成的?
  • ¥30 STK matlab python仿真
  • ¥15 关于IMageEnView 图标定位问题
  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题