2015-12-02 43 views
1

我通過SOAP獲得不同的XML字符串。simplexml_load_string值爲的路徑

但是我很難從PHP獲得XML的價值。

XML實例:

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<soap:Body> 
    <GetUserInfoResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"> 
     <GetUserInfoResult> 
      <GetUserInfo> 
       <User ID="23" /> 
      </GetUserInfo> 
     </GetUserInfoResult> 
    </GetUserInfoResponse> 
</soap:Body> 
</soap:Envelope> 


<?xml version = "1.0" encoding = "utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Body> 
     <GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/"> 
      <GetListItemsResult> 
       <listitems xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' 
    xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' 
    xmlns:rs='urn:schemas-microsoft-com:rowset' 
    xmlns:z='#RowsetSchema'> 
        <rs:data> 
         <z:row ows_ID="128" /> 
        </rs:data> 
       </listitems> 
      </GetListItemsResult> 
     </GetListItemsResponse> 
    </soap:Body> 
</soap:Envelope> 

我想獲得的ID。

我想它是這樣的:

$xml_element = simplexml_load_string($responseContent); 
$name_spaces = $xml_element->getNamespaces(true); 
$soap = $xml_element->children($name_spaces['soap']) 
    ->Body 
    ->children($name_spaces['rs']) 
    ->GetListItemsResponse 
    ->GetListItemsResult 
    ->listitems 
    ->{'rs:data'} 
    ->{'z:row'}['ows_ID'][0]; 

但大部分時間我不知道如何讓我的價值。

是否可以顯示整個數組或如何獲取值的路徑?

回答

0

你可以做得到「ows_ID」的值是使用SimpleXMLElementchildren方法,並且還添加了命名空間的子元素。

您可以使用attributes方法獲取'ows_ID'的值;

例如:

$responseContent = <<<XML 
<?xml version = "1.0" encoding = "utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soap:Body> 
     <GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/"> 
      <GetListItemsResult> 
       <listitems xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' 
    xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' 
    xmlns:rs='urn:schemas-microsoft-com:rowset' 
    xmlns:z='#RowsetSchema'> 
        <rs:data> 
         <z:row ows_ID="128" /> 
        </rs:data> 
       </listitems> 
      </GetListItemsResult> 
     </GetListItemsResponse> 
    </soap:Body> 
</soap:Envelope> 
XML; 

$xml_element = simplexml_load_string($responseContent); 
$name_spaces = $xml_element->getNamespaces(true); 

$rows = $xml_element 
    ->children($name_spaces['soap']) 
    ->Body 
    ->children() 
    ->GetListItemsResponse 
    ->GetListItemsResult 
    ->listitems 
    ->children($name_spaces['rs']) 
    ->children($name_spaces['z']); 

foreach ($rows as $row) { 
    $ows_ID = $row->attributes()->ows_ID; 
} 

Demo