2016-06-10 54 views
2

我需要將XML轉換爲陣,但其未進行轉換XML到陣列使用simplexml_load_string

這裏是我的代碼

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

但是,如果我從XML刪除

<soap:Body> 

它工作正常,如何解決它的問題是什麼

+0

的[解析與使用SimpleXML命名空間XML]可能的複製(http://stackoverflow.com/questions/ 595946/parse-xml-with-namespace-using-simplexml) – CBroe

+0

不幸的是,當涉及命名空間時,SimpleXML不再簡單。有可能你不能使用'json_encode($ xml)'技巧。您是否真的需要針對任何XML定義的通用解決方案? –

+0

@AlvaroGonzalez有沒有其他可用的替代品? –

回答

1

嘗試類似解決方案從這個question

你的情況,試試這個代碼

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

     ) 

)