首页 >后端开发 >php教程 >如何在 Guzzle 6 中检索响应主体?

如何在 Guzzle 6 中检索响应主体?

Susan Sarandon
Susan Sarandon原创
2024-11-30 17:06:12534浏览

How to Retrieve the Response Body in Guzzle 6?

在 Guzzle 6 中检索响应正文

Guzzle 6 是一个流行的 PHP HTTP 客户端库,它使用强制使用流的 PSR-7 标准存储消息的正文。要以字符串形式检索此正文,请使用以下方法之一:

字符串转换运算符

$contents = (string) $response->getBody();

使用 getContents()

$contents = $response->getBody()->getContents();

Key差异:

  • getContents() 返回剩余内容流的,这意味着后续调用将返回空字符串,除非使用倒带或查找重置流位置。
  • 转换为字符串将从流中读取所有数据,无论之前的操作如何。

例如:

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all contents
$contents = $stream->getContents(); // empty string
$stream->rewind();  // reset stream position
$contents = $stream->getContents();  // returns all contents again

对比:

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

了解更多详细信息,请参阅 Guzzle 文档:http://docs.guzzlephp.org/en/latest/psr7.html#responses

以上是如何在 Guzzle 6 中检索响应主体?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn