michaelhall/page-fetcher

This package is abandoned and no longer maintained. The author suggests using the michaelhall/http-client package instead.

Simple web page fetcher

v1.0.0 2018-02-09 19:32 UTC

This package is auto-updated.

Last update: 2022-02-01 13:10:45 UTC


README

Build Status codecov.io Maintainability StyleCI License Latest Stable Version Total Downloads

A simple web client.

Requirements

  • PHP >= 7.1

Install with Composer

$ composer require michaelhall/page-fetcher

Basic usage

Fetch a page

<?php

require_once __DIR__ . '/vendor/autoload.php';

$pageFetcher = new \MichaelHall\PageFetcher\PageFetcher();

$url = \DataTypes\Url::parse('https://example.com/');
$request = new \MichaelHall\PageFetcher\PageFetcherRequest($url);
$response = $pageFetcher->fetch($request);

// Prints "success" if request was successful, "fail" otherwise.
echo $response->isSuccessful() ? 'success' : 'fail';

// Prints the response content.
echo $response->getContent();

// Prints the http code, e.g. 200.
echo $response->getHttpCode();

// Prints the headers.
foreach ($response->getHeaders() as $header) {
    echo $header;
}

Customize the request

// Set the method.
$request = new \MichaelHall\PageFetcher\PageFetcherRequest($url, 'POST');

// Set a POST field.
$request->setPostField('Foo', 'Bar');

// Set a file.
$request->setFile('Baz', \DataTypes\FilePath::parse('/path/to/file'));

// Add a header.
$request->addHeader('Content-type: application/json');

// Set raw content.
$request->setRawContent('{"Foo": "Bar"}');

Use the fake page fetcher for application testing

<?php

require_once __DIR__ . '/vendor/autoload.php';

$pageFetcher = new \MichaelHall\PageFetcher\FakePageFetcher();
$pageFetcher->setResponseHandler(function ($request) {
    return new \MichaelHall\PageFetcher\PageFetcherResponse(200, 'Request url is ' . $request->getUrl());
});

$url = \DataTypes\Url::parse('https://example.com/');
$request = new \MichaelHall\PageFetcher\PageFetcherRequest($url);
$response = $pageFetcher->fetch($request);

// Prints "Request url is https://example.com/".
echo $response->getContent();

Both the PageFetcher and FakePageFetcher classes implements the \MichaelHall\PageFetcher\Interfaces\PageFetcherInterface interface, making it possible to use for dependency injection in the application.

License

MIT