PHP
HTTP

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

More than 1 year has passed since last update.

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"}"