Last Updated: January 25, 2021
·
882
· kalinin84

Fetch internet resources

<?php

class Client
{
    /**
     * @param string $url
     * @param string $userAgent
     * @return string
     */
    public function fetch($url, $userAgent)
    {
        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_USERAGENT, $userAgent);
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 5);
        $result = curl_exec($handle);
        curl_close($handle);

        return $result;
    }
}
<?php

// composer require guzzlehttp/guzzle:~6.0
require 'vendor/autoload.php';

class Client
{
    /**
     * @param string $url
     * @param string $userAgent
     * @return string
     */
    public function fetch($url, $userAgent)
    {
        $client = new GuzzleHttp\Client();
        $headers = ['User-Agent' => $userAgent];
        $res = $client->request('GET', $url, ['headers' => $headers]);

        return (string) $res->getBody();
    }
}
<?php

class Client
{
    /**
     * @param string $url
     * @return string
     */
    public function fetch($url)
    {
        return file_get_contents($url);
    }
}