2014-09-28 137 views
1

我有一個使用SOAP從遠程服務器獲取信息的PHP腳本。在弄清楚如何使用SOAP之後,我被卡住了發送的響應。我無法解析數據,因爲看起來我的數組是一個對象數組。我將如何能夠正確解析數據?對象多維數組

代碼:

[1]=> object(stdClass)#5 (19) { ["ID"]=> int(200) 
["Title"]=> string(13) "Test" ["StartTimeUTC"]=> string(20) "2014-09-24 05:00:00Z"  
["EndTimeUTC"]=> string(20) "2014-09-27 05:00:00Z" ["OwnerId"]=> int(10) 
["UserName"]=> string(13) "testuser" ["FirstName"]=> string(7) "Test" 
["LastName"]=> string(12) "User" ["Email"]=> string(27) 
"[email protected]" ["ServiceType"]=> string(7) "Default" } 

*最新代碼

$wsdl = 'https://192.168.1.10/requests.asmx?WSDL'; 

$trace = true; 
$exceptions = false; 

$xml_array['StartTime'] = "2014-01-27T00:00:00"; 
$xml_array['EndTime'] = "2014-09-27T23:59:00";  

$login = 'test'; 
$password = 'test'; 

try 
{ 
    $client = new SoapClient($wsdl, array('login' => $login, 'password' => $password, 'trace' => $trace, 'exceptions' => $exceptions)); 
    $response = $client->GetAll($xml_array); 
} 

catch (Exception $e) 
{ 
    echo "Error!"; 
    echo $e -> getMessage(); 
    echo 'Last response: '. $client->__getLastResponse(); 
} 

function objectToArray($response) 
{ 
if (is_object($response)) 
    $response = get_object_vars($response); 
if (is_array($response)) 
    return array_map(__FUNCTION__, $response1); 
else 
    return $response; 
} 

$array = objectToArray($response); 

echo $array['0']['Title']; 

print_r($array); 

服務器RES:從服務器

<?php 

$wsdl = 'https://192.168.1.10/requests.asmx?WSDL'; 

$trace = true; 
$exceptions = false; 

$xml_array['StartTime'] = "2014-01-27T00:00:00"; 
$xml_array['EndTime'] = "2014-09-27T23:59:00";  

$login = 'test'; 
$password = 'test'; 

try 
{ 
    $client = new SoapClient($wsdl, array('login' => $login, 'password' => $password, 'trace' => $trace, 'exceptions' => $exceptions)); 
    $response = $client->GetAll($xml_array); 
} 

catch (Exception $e) 
{ 
    echo "Error!"; 
    echo $e -> getMessage(); 
    echo 'Last response: '. $client->__getLastResponse(); 
} 

//echo $response->["Title"]; 

//var_dump($response); 


?> 

響應從最新的代碼ponse:

Array ([GetAll] => Array ([Conference] => Array ([0] => Array ( 
[ConferenceId] => 1 [Title] => Test [StartTimeUTC] => 2014-05-23 11:36:15Z 
[EndTimeUTC] => 2014-05-23 12:06:15Z 
[OwnerId] => 2 [UserName] => testuser [FirstName] => Test 
[LastName] => User [Email] => [email protected] 
[ServiceType] => Default) 

回答

2

1解決方案

使用此功能轉換的objectarray

/** 
* @param Obj  The object to convert 
* @return Array The converted array 
*/ 
function objectToArray($obj) 
{ 
    if (is_object($obj)) 
     $obj = get_object_vars($obj); 
    if (is_array($obj)) 
     return array_map(__FUNCTION__, $obj); 
    else 
     return $obj; 
} 

第二個解決方案

對JSON對象,你可能想要使用json_decode

json_decode($jsonObj); 

從文檔:

返回值

返回相應的PHP類型JSON編碼值。值true,false和null分別作爲TRUE,FALSE和NULL返回。如果json無法解碼或者編碼數據比遞歸限制更深,則返回NULL。

3解決方案

只有當你的對象屬性市民:

$array = (array) $object;