场景:REST api,客户端通过GET方法从服务器请求数据
我从HomeController返回一个数组(服务器端:Laravel 5)
return ['Status' => 'Success', 'SearchResponse' => $apiresponse, 'AuthToken' => $property];
以上回复是通过网址http://example.com/flightSearch
在客户端(Laravel 4)
$input=Input::all();
$url = 'http://example.com/flightSearch';
$data = array(
'client_id' => 'XXX',
'api_secret' => 'YYY',
'method'=>'SearchFlight',
'adult'=>$input['adult'],
'children'=>$input['children'],
'infant'=>$input['infant'],
'departCity'=>$input['departCity'],
'arrivalCity'=>$input['arrivalCity'],
'departDate'=>$input['departDate'],
'returnDate'=>$input['returnDate'],
'journeyType'=>$input['journeyType']
);
$params = http_build_query($data);
$result = file_get_contents($url.'?'.$params);
$response = json_decode($result);
return $response->Status //Works
return $response->AuthToken //Works
return $response->SearchResponse //Throws following Error
错误:
The Response content must be a string or object implementing __toString()
解决方案:
变量$apiresponse
是从远程服务器返回的对象。将变量添加到对象解决了问题
return ['Status' => 'Success', 'SearchResponse' => array($apiresponse), 'AuthToken' => $property];
答案 0 :(得分:3)
由于你有一个JSON字符串,你只需使用json_decode()
:
$response = json_decode($result);
return $response->Status;
Response内容必须是实现__toString()
的字符串或对象
这只是因为您从控制器操作中返回$response->SearchResponse
。像$response->SearchResponse->SomeProperty
一样使用它就可以了。无需array($apiresponse)
如果您想查看该变量的所有内容,请使用var_dump()
:
var_dump($response->SearchResponse);
假设您使用Laravels帮助创建了$response
,这应该是Illuminate\Http\JsonResponse
的实例。
您可以使用getData()
获取数据(已解码):
$data = $response->getData();
echo $data->Name
答案 1 :(得分:0)
$test1 = array('name'=>'gggg');
print_r($test1); //answer: Array ([name]=>gggg)
$test2 = json_encode($test1);
print_r($test2); //answer: {"name":"gggg"}
$test3 = json_decode($test2);
echo $test3->name; //answer: gggg