Guzzle 返回值取值解析

宰父玄天
2023-12-01

Guzzle实现了PSR-7。 这意味着它将默认将消息正文存储在使用PHP临时流的Stream中。 要检索所有数据,可以使用类型转换操作符。

示例:
$client = new Client($this->getOptions());
$response = $client->request($method, $url, $options);

我们可以有两种取值方式如下:

$contents = (string) $response->getBody();
// or
$contents = $response->getBody()->getContents();

两种方法之间的区别在于使用了getContents方法是返回剩余的内容,因此第二次调用不返回任何内容,除非您使用rewind方法或查找流的位置seek方法将流指针倒回开始位置。

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

相反,使用PHP的字符串转换操作,它将从开头读取流中的所有数据,直到到达结尾。

$contents = (string) $response->getBody(); // returns all the contents

文档:http://docs.guzzlephp.org/en/latest/psr7.html#responses
参考:https://stackoverflow.com/questions/30549226/guzzlehttp-how-get-the-body-of-a-response-from-guzzle-6

 类似资料: