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 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件