LoginSignup
0
0

PHP: guzzlehttp/guzzle の使い方

Posted at

次のページと同じことを Ubuntu 23.04 で行いました。
PHP Http ClientのGuzzleパッケージを使う

ライブラリーのインストール

composer require guzzlehttp/guzzle

作成された composer.json

composer.json
{
    "require": {
        "guzzlehttp/guzzle": "^7.8"
    }
}

テストプログラム

check01.php
#! /usr/bin/php
<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');

echo $response->getBody();

?>

実行結果

$ ./check01.php 
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"

Httpie で同じリクエストを発行する

$ http https://jsonplaceholder.typicode.com/posts/1
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Age: 5591
CF-Cache-Status: HIT
CF-RAY: 80b9bf0be94df583-NRT
Cache-Control: max-age=43200
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Sep 2023 08:44:34 GMT
Etag: W/"124-yiKdLzqO5gfBrJFrcdJ8Yq0LGnU"
Expires: -1
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Pragma: no-cache
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=q4EGse%2F7X%2FKbBpDTbGwWcY2%2B5dz%2Bn1cPOE7P31KLFzztbanJdUjgxHe8KIwVnkYQE%2FXFMCQzT54vUngzwkhrKBVcLAmw1txwShE4Ck23bDYTLiJGmRjUleDUOEzULFOkXRKq6tJAKec1PaSCWRB1Xqm2X%2FY2e4h8WsaR"}],"group":"cf-nel","max_age":604800}
Server: cloudflare
Transfer-Encoding: chunked
Vary: Origin, Accept-Encoding
Via: 1.1 vegur
X-Content-Type-Options: nosniff
X-Powered-By: Express
X-Ratelimit-Limit: 1000
X-Ratelimit-Remaining: 999
X-Ratelimit-Reset: 1691790101
alt-svc: h3=":443"; ma=86400

{
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "userId": 1
}

確認したバージョン

$ php --version
PHP 8.1.12-1ubuntu4.3 (cli) (built: Aug 17 2023 17:37:48) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.12, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.12-1ubuntu4.3, Copyright (c), by Zend Technologies
0
0
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
0
0