我有一个PHP脚本,它使用SOAP从远程服务器获取信息。在弄清楚如何使用SOAP之后,我对发送的响应感到困惑。我无法解析数据,因为看起来我的数组是一个对象数组。我怎样才能正确解析数据?
代码:
<?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);
?>
来自服务器的响应:
[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)
"test.user@my.lab" ["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);
来自最新代码的服务器响应:
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] => test.user@me.lab
[ServiceType] => Default )
答案 0 :(得分:2)
第一个解决方案
使用此功能将object
转换为array
:
/**
* @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。
第三个解决方案
仅当您的对象属性是公共的时:
$array = (array) $object;