我想通过Guzzle从方法sendAsync返回响应,但是它返回空。
public function getliveflight_guzzle()
{
$url = 'https://www.tesflight.com/ajax/pingFlightSearch?d=CGK&a=DPS&date=2018-08-18&adult=1&child=0&infant=0&service_class=&airlines=["MALAYSIAAIR"]&subsidy=true&page_view=roundseperate&refund_deposit=&refund_currency=';
$client = new Client(['headers' => ['Accept' => 'application/json, text/javascript, */*; q=0.01', 'Accept-Language' => 'en-us,en;q=0.5', 'X-Requested-With' => 'XMLHttpRequest']]);
// Send an asynchronous request.
$request = new Psr7\Request('GET', $url, [
'curl' => [
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => '0',
CURLOPT_SSL_VERIFYPEER => '0',
CURLOPT_AUTOREFERER => TRUE,
CURLINFO_HEADER_OUT => true,
CURLOPT_FOLLOWLOCATION => '1',
CURLOPT_VERBOSE => true
]
]);
$promise = $client->sendAsync($request)->then(function ($response) {
return $response->getBody()->getContents();
});
$promise->wait();
}
public function actionTesguzzle()
{
$response = $this->getliveflight_guzzle();
$response = json_decode($response, TRUE);
print_r($response);
}
我也想尝试将$ response-> getBody()-> getContents()保存到变量中,然后尝试在sendAsync方法外回显它,但它显示为空。但是,如果我在sendAsync内部回显它,它将显示数据。怎么会这样?
请帮助。
答案 0 :(得分:0)
您应该从函数return $promise->wait();
返回值,请尝试以下操作:
public function getliveflight_guzzle()
{
$url = 'https://www.tesflight.com/ajax/pingFlightSearch?d=CGK&a=DPS&date=2018-08-18&adult=1&child=0&infant=0&service_class=&airlines=["MALAYSIAAIR"]&subsidy=true&page_view=roundseperate&refund_deposit=&refund_currency=';
$client = new Client(['headers' => ['Accept' => 'application/json, text/javascript, */*; q=0.01', 'Accept-Language' => 'en-us,en;q=0.5', 'X-Requested-With' => 'XMLHttpRequest']]);
// Send an asynchronous request.
$request = new Psr7\Request('GET', $url, [
'curl' => [
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17',
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYHOST => '0',
CURLOPT_SSL_VERIFYPEER => '0',
CURLOPT_AUTOREFERER => TRUE,
CURLINFO_HEADER_OUT => true,
CURLOPT_FOLLOWLOCATION => '1',
CURLOPT_VERBOSE => true
]
]);
$promise = $client->sendAsync($request)->then(function ($response) {
return $response->getBody()->getContents();
});
return $promise->wait();
}
public function actionTesguzzle()
{
$response = $this->getliveflight_guzzle();
$response = json_decode($response, TRUE);
print_r($response);
echo json_last_error_msg();
}
您还可以使用函数json_last_error_msg()调试json的解码