2012-02-29 458 views
-1

使用simplexml傳遞SOAP響應之後,我得到了以下輸出。我怎樣才能得到域的屬性值,即名稱和效用。使用使用Simple XML解析SOAP響應PHP

代碼:在返回

$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $result);  
     $xml = simplexml_load_string($xmlString); 
     print_r($xml); 



SimpleXMLElement Object([soapBody] => SimpleXMLElement Object ([CheckAvailabilityResponse] => SimpleXMLElement Object([CheckAvailabilityResult] => &lt;?xml version="1.0" encoding="UTF-16"?&gt; 
&lt;check&gt; 
    &lt;domain name="MYNAMEISNIJIL.COM" avail="1" canBackorder="0"/&gt; 
&lt;/check&gt;))) 

回答

3

顯然,你已經逃脫XML(這是一個不好的做法,我會忽略現在..)。此外,尋找到children()函數的命名空間,而不是你preg_replace工作....忽略了,這會爲你工作:

$outerxml = simplexml_load_string($xmlString); 
    $innerxml = simplexml_load_string(htmlspecialchars_decode(
    $outerxml->soapBody->CheckAvailabilityResponse->CheckAvailabilityResult)); 

在一個側面說明,我通常使用這個珍聞利用SOAPClient解析SOAP響應:

//the soap way 
class SneakyFauxSoap extends SoapClient { 
    public $response; 
    function __doRequest($val){ 
     return $this->response; 
    } 
} 

$soap = new SneakyFauxSoap(null, 
    array(
     'uri' =>'something', 
     'location'=>'something', 
     'soap_version' => SOAP_1_1)); 
$soap->response = $x; 
var_dump($soap->somerandomfunction()); 
+0

+1對於醜陋而又巧妙的SneakyFauxSoap hack :) – Sergio 2012-10-31 13:46:22

0

通過@ Wrikken的回答啓發,我寫了一個簡單易用的類,它使用PHP 5.3的工作 :

class SoapParser extends SoapClient { 
    private $xml; 

    function __construct($options) { 
    $options['location'] = $options['uri'] = 'dummy'; 
    parent::__construct(null, $options); 
    } 

    public function __doRequest($request, $location, $action, $version, 
           $one_way = 0) 
    { 
    return $this->xml; 
    } 

    public function parse($xml) { 
    $this->xml = $xml; 
    return $this->dummyFunction(); 
    } 
} 

使用示例:

$soapParser = new SoapParser(array('soap_version' => 'SOAP_1_1')); 
try { 
    var_dump($soapParser->parse($response)); 
} catch (Exception $e) { 
    die($e->getMessage()); 
}