yano3nora
7/2/2017 - 8:25 AM

[php: HTTPClient Guzzle] WordPressとかのRSSを読んでどうこうするやつだったはず。 #php #guzzle #wordpress

[php: guzzle] Guzzle, an extensible PHP HTTP client. #php

OVERVIEW

guzzle/guzzle - github.com
Guzzle Documentation

PHP 製の有名な HTTP クライアント。非同期のリクエスト送信や PSR-7 準拠の実装にも対応していたりとモダンでイイ感じ。

Requirements

  • curl 7.19.4 以上
  • php 5.5.0 以上
  • php.iniallow_url_fopen=enable を指定

Installation

$ composer require guzzlehttp/guzzle

Usage

use GuzzleHttp\Client;

// Init
$client = new Client([
    'base_uri'    => 'http://example.com/api',
    'timeout'     => 2.0,  // sec
]);

// Sync request.
$response = $client->get('test');    // GET http://example.com/api/test
$response = $client->post('/root');  // POST http://example.com/root

// Querystring.
$client->get($url, [
    'query' => ['foo' => 'bar']
]);

// POST params.
$r = $client->put($url, [
    'json' => ['foo' => 'bar']
]);
$response = $client->post($url, [
    'form_params' => [
        'field_name' => 'abc',
        'other_field' => '123',
        'nested_field' => [
            'nested' => 'hello'
        ]
    ]
]);

// POST multipart/form-data
$response = $client->post($url, [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);

URI

base_uri と各リクエストの URI は末尾 / 含め厳格にルールが分かれているので注意。

base_uriURIResult
http://foo.com/barhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/bar
http://foo.com/foobarhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/foo/bar
http://foo.comhttp://baz.comhttp://baz.com
http://foo.com/?barbarhttp://foo.com/bar

Asynchronous

$promise = $client->getAsync('http://httpbin.org/get');
$promise->then(
    function (\Psr\Http\Message\ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (\GuzzleHttp\Exception\RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);


TIPS & REFERENCES

Options

Request Options

$client->get('/', [
    'http_errors' => trye,   // Throws exception on 4xx ~ 5xx.
    'verify'      => true,   // Throws exception on invalid certs.
    'debug'       => false,  // Print logs to stdout.
    'headers'     => [
        'Content-Type: application/json',
    ],
    'config'      => [       // @see http://bit.ly/2MDjnQY
        'curl'    => [
            'CURLOPT_NOBODY' => true,
        ],
    ],
    'sink'         => '/path/to',  // Specify path the response will be saved.
]);

Exceptions

Exceptions

Handlers / Middleware

Handlers and Middleware

PSR-7

Guzzle and PSR-7