Skip to content

Instantly share code, notes, and snippets.

Created July 15, 2022 16:05
What would you like to do?
Fetch the contents of a single file from a Github repo using Guzzle and return as a string
use \GuzzleHttp\Client;
use \GuzzleHttp\Psr7;
use \GuzzleHttp\Exception\RequestException;
* Use guzzle to get a single file from github and return it as a string.
* @param string $url The path of the file to fetch
* @return string
* @throws \Exception
public function fetchFileFromGithub(string $url):string
try {
$response = $this->guzzle->request('GET', $url, [
'auth' => [
$this->githubUser, //<-- replace with your username
$this->githubToken, //<-- replace with your Github Personal Access Token
'headers' => [
'Accept' => 'application/vnd.github.v3.raw', //<-- This gets you the raw contents of the file.
'User-Agent' => 'Your-Application', //<-- Github wants a user agent.
} catch (ClientException $e) {
throw new \Exception('Guzzle problem: ', Psr7\Message::toString($e->getRequest()), Psr7\Message::toString($e->getResponse()));
if ($response->getStatusCode() == '200') {
return (string) $response->getBody();
} else {
throw new \Exception('Guzzle bad response code');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment