LoginSignup
14
4

More than 5 years have passed since last update.

Guzzleのリクエストを再現するcurlコマンドを生成する。

Last updated at Posted at 2016-11-17

小ネタです。
GuzzleでHTTPリクエストを実行したときに、それと同じリクエストを生成するcurlコマンドが欲しい場合があります。

Cuzzle を使うと、Guzzleで実行したリクエストと同等のcurlコマンドを出力することができます。

install

composerで一発。

$ composer require namshi/cuzzle

使い方

<?php
// composer.jsonはよしなに…。
require_once './vendor/autoload.php';

// ロガーの設定
$logger = (new \Monolog\Logger('guzzle.to.curl'))
            ->pushHandler($curl_logger = new \Monolog\Handler\TestHandler());

// Guzlleのイベントハンドラにロガーを設定して、curlフォーマッタを指定。
$handler = \GuzzleHttp\HandlerStack::create();
$handler->after('cookies', new \Namshi\Cuzzle\Middleware\CurlFormatterMiddleware($logger));

// Guzlleクライアントにイベントハンドラを指定。
$client = new \GuzzleHttp\Client(['base_uri' => "http://www.example.com", 'handler' => $handler]);

// リクエスト実行
$response = $client->request('POST', "/v1/hoges", [
    'form_params' => [
        'param1' => 'abc',
        'param2' => 'def'
    ]
]);

// 結果を出力
$records = $curl_logger->getRecords();
echo $record[0]['message'];
結果
curl 'http://www.example.com/v1/hoges' -A 'GuzzleHttp/6.2.1 curl/7.49.1 PHP/7.0.12' \
  -H 'Content-Type: application/x-www-form-urlencoded' -X POST -d 'param1=abc&param2=def'

もちろんContent-Type: application/x-www-form-urlencodedやPOSTメソッドだけではなく、json形式や他のメソッドにも対応しています。

(差し替え部分)
$response = $client->request('PUT', "/v1/fuga", [
    'json' => [
        'param1' => 'abc',
        'param2' => 'def'
    ]
]);
結果
curl 'http://www.example.com/v1/fuga' -A 'GuzzleHttp/6.2.1 curl/7.49.1 PHP/7.0.12' \
  -H 'Content-Type: application/json' -X PUT -d '{"param1":"abc","param2":"def"}
14
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
4