Skip to content

Instantly share code, notes, and snippets.

@imonroe
Created July 15, 2022 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imonroe/666c0ef551a69e1e86c2c75b8a01d1e9 to your computer and use it in GitHub Desktop.
Save imonroe/666c0ef551a69e1e86c2c75b8a01d1e9 to your computer and use it in GitHub Desktop.
Fetch the contents of a single file from a Github repo using Guzzle and return as a string
<?php
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