PHP code example of spindle / httpclient

1. Go to this page and download the library: Download spindle/httpclient library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spindle / httpclient example snippets


$request = new Spindle\HttpClient\Request('http://example.com/api', array(
  'post' => true,
  'postFields' => http_build_query(array(
    'param' => 'value',
  )),
));

$response = $request->send();

$statusCode = $response->getStatusCode();
$header     = $response->getHeaderString();
$body       = $response->getBody();
$body       = (string)$response;


//libcurl original
$ch = curl_init('http://example.com/api');
curl_setopt_array($ch, array(
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER => true,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => http_build_query(array(
    'param' => 'value',
  )),
));

$response_fulltext = curl_exec($ch);
curl_close($ch);

$req1 = new Spindle\HttpClient\Request('http://example.com/');
$req2 = clone $req1;

$req = new Spindle\HttpClient\Request;

//equals
$req->setOption(CURLOPT_POST, true);
$req->setOption('post', true);

//equals
$req->setOption(CURLOPT_POSTFIELDS, 'a=b');
$req->setOption('postFields', 'a=b');

$req = new Spindle\HttpClient\Request();
$req->setOptions(array(
  'post' => true,
  'postFields' => 'a=b',
));

use Spindle\HttpClient;

$pool = new HttpClient\Multi(
    new HttpClient\Request('http://example.com/api'),
    new HttpClient\Request('http://example.com/api2')
);
$pool->setTimeout(10);

$pool->send(); //wait for all response

foreach ($pool as $url => $req) {
    $res = $req->getResponse();
    echo $url, PHP_EOL;
    echo $res->getStatusCode(), PHP_EOL
    echo $res->getBody(), PHP_EOL;
}

use Spindle\HttpClient;

$pool = new HttpClient\Multi;
$req1 = new HttpClient\Request('http://example.com/api1');
$req2 = new HttpClient\Request('http://example.com/api2');

$pool->attach($req1);
$pool->attach($req2);

$pool->detach($req1);

$pool->send();

use Spindle\HttpClient;

$pool = new HttpClient\Multi(
    new HttpClient\Request('http://example.com/api'),
    new HttpClient\Request('http://example.com/api2')
);

$pool->start();

for ($i=0; $i<10000; $i++) {
    very_very_heavy_function();
    $pool->start();
}

$pool->waitResponse();

foreach ($pool as $req) {
    $res = $req->getResponse();
    echo "{$res->getStatusCode()}\t{$res->getUrl()}\t{$res->getBody()}\n";
}