LoginSignup
2
1

More than 5 years have passed since last update.

PHP で Python-Requests な感じで HTTP リクエストをする

Posted at

Requests for PHP を使う。

install

$ composer require rmccue/requests
Using version ^1.7 for rmccue/requests
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing rmccue/requests (v1.7.0): Loading from cache
Writing lock file
Generating autoload files

使ってみる

サンプルコードを使ってみる。 

index.php
<?php
require 'vendor/autoload.php';

$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);

var_dump($request->status_code);
// int(200)

var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"

var_dump($request->body);
// string(26891) "[...]"

gistをとってくるけど、auth 情報を書き換えてないので 401 が帰ってくる。

実行結果はこんな感じ。

 $ php index.php
int(401)
string(31) "application/json; charset=utf-8"
string(83) "{"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}"
2
1
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
2
1