我正在尝试构建一个端点,使用Slim PHP框架将传递给它的数据转发到API,但我无法从Guzzle请求中获取响应。
$app->map( '/api_call/:method', function( $method ) use( $app ){
$client = new GuzzleHttp\Client([
'base_url' => $app->config( 'api_base_url' ),
'defaults' => [
'query' => [ 'access_token' => 'foo' ],
]
]);
$request = $client->createRequest( $app->request->getMethod(), $method, [
'query' => $app->request->params()
]);
var_dump( $client->send( $request )->getBody() );
})->via( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' )->conditions( [ 'route' => '.+?' ] );`
然后这给了我......
object(GuzzleHttp\Stream\Stream)[59]
private 'stream' => resource(72, stream)
private 'size' => null
private 'seekable' => boolean true
private 'readable' => boolean true
private 'writable' => boolean true
private 'meta' =>
array (size=6)
'wrapper_type' => string 'PHP' (length=3)
'stream_type' => string 'TEMP' (length=4)
'mode' => string 'w+b' (length=3)
'unread_bytes' => int 0
'seekable' => boolean true
'uri' => string 'php://temp' (length=10)
...而不是我所期待的'酷'的反应。
如果我只是var_dump $client->sendRequest( $request )
我得到200 OK,并且网址是我所期望的,http://localhost:8000/test?access_token=foo
。
我有另一个请求,但只使用$client->post(...)
,它工作正常,而不给我流回来的东西。
我尝试使用底部的示例(http://guzzle.readthedocs.org/en/latest/http-client/response.html)读取流,但它告诉我feof
不存在。
任何人都知道我在这里错过了什么或做错了什么?
你是var_dumping的主体是一个Guzzle流对象。可以将此对象视为字符串或根据需要进行读取。 Documentation for Guzzle Stream here
可能;
$response = $client->send($request)->getBody()->getContents();
$response = $client->send($request)->getBody()->read(1024*100000);
这也是一种速记;
$response = ''. $client->send($request)->getBody();
$response = (string) $client->send($request)->getBody();
//参见最后一个例子的__toString()
方法:http://php.net/manual/en/language.oop5.magic.php#object.tostring
我遇到了同样的问题,问题是,如果你把它变成了一个流,这意味着它有一个指针,当你对其执行getContents时它将指针留在文件的末尾,这意味着如果你想获得身体多次需要寻找指针回0。
$html1 = $this->response->getBody()->getContents();
$this->response->getBody()->seek(0);
$html2 = $this->response->getBody()->getContents();
$this->response->getBody()->seek(0);
这应该工作:)
@mrW我希望这会对你有所帮助
只是有一个奇怪的情况。请注意,您只能获取一次身体内容!
我每次打电话给getContents()
时都希望能得到相同的内容。
$html1 = $this->response->getBody()->getContents();
$html2 = $this->response->getBody()->getContents();
$same = ($html1 == $html2);
strlen($html1); //x
strlen($html2); //0
但他们不是!我错过了Guzzle响应是stream
的信息,所以我们首先阅读getContents()
所有内容,没有留下第二个电话。