1

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

alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
vellai durai
  • 1,019
  • 3
  • 16
  • 38
  • Possible duplicate of [Parse XML with Namespace using SimpleXML](http://stackoverflow.com/questions/595946/parse-xml-with-namespace-using-simplexml) – CBroe Jun 10 '16 at 12:50
  • Unfortunately, SimpleXML is no longer simple when namespaces are involved. It's possible that you simply cannot use the `json_encode($xml)` trick. Do you really need to generic solution for any XML definition? – Álvaro González Jun 10 '16 at 12:53
  • @AlvaroGonzalez Is there any alternate available? – vellai durai Jun 10 '16 at 17:15

1 Answers1

1

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
                )

        )

)
Community
  • 1
  • 1
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46