[PHP]Guzzleで応答データのレスポンスボディをstring型として取得する

カテゴリ: GuzzleHttp

PHPでのHTTPリクエストを行うライブラリにGuzzleHTTPが有ります。

GuzzleHTTPでは、通常以下のようなコードで応答テキストを出力することが多いです。

<?php
# test.php
require "vendor/autoload.php";

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com');
echo $response->getBody();

実行結果

> composer require guzzlehttp/guzzle
Using version ^6.3 for guzzlehttp/guzzle
./composer.json has been created
...
Writing lock file
Generating autoload files


> php test.php
<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

上記のコードを見るとgetBody()が応答データを文字列として渡していそうですが、そうではありません。
get_class()や、is_string()で確認すると、stringではなくGuzzleHttp\Psr7\Streamクラスのオブジェクトであることがわかります。

<?Php
require "vendor/autoload.php";

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com');

$body = $response->getBody();
echo get_class($body) . PHP_EOL;
var_dump(is_string($body));

実行結果

> php test.php

GuzzleHttp\Psr7\Stream
bool(false)

echoメソッドはストリームを渡されても結果を出力できるため、文字列が返されているのかと勘違いしているだけでした。

この出力ストリームを文字列に変換するには、以下の様にgetContents()メソッドを呼べばよいです。

<?Php
require "vendor/autoload.php";

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com');

$bodyStr = $response->getBody()->getContents();
var_dump(is_string($bodyStr));

実行結果

> php test.php

bool(true)

Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です