使用simplexml_load_string的XML数组 [英] XML to array using simplexml_load_string

查看:105
本文介绍了使用simplexml_load_string的XML数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将XML转换为数组,但不能转换

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

这是我的代码

<?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); 

但是,如果我删除

<soap:Body> 

从XML正常工作,如何重命名它是什么问题

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

推荐答案

尝试从此在您的情况下,请尝试此代码

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);

输出将是:

Array
(
    [Search] => Array
        (
            [Request] => Array
                (
                    [aaa] => string
                    [bbb] => string
                    [ccc] => srting
                    [SourceName] => string
                )

        )

)

这篇关于使用simplexml_load_string的XML数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆