Skip to content

Instantly share code, notes, and snippets.

@phcorp
Created April 27, 2017 13:52
Show Gist options
  • Save phcorp/719b9268e23f76cdcf068b50d1d685c0 to your computer and use it in GitHub Desktop.
Save phcorp/719b9268e23f76cdcf068b50d1d685c0 to your computer and use it in GitHub Desktop.
API functions
<?php
/**
* @param string $path prepended with a slash
* @param string $data to send
* @param string $method default POST
* @param string $header to send
*
* @return string response
*/
function request($path, $data = null, $method = 'POST', $header = null)
{
$context = stream_context_create([
'http' => [
'method' => $method,
'header' => $header,
'content' => $data,
]
]);
return file_get_contents($path, false, $context);
}
/**
* @param string $path prepended with a slash
* @param array $data serializable
* @param string $method default POST
* @param array $headers to send
*
* @return array response
*/
function requestJson($path, array $data = [], $method = 'POST', array $headers = [])
{
$headers['Content-Type'] = 'application/json; charset=utf-8';
$headers['Accept'] = 'application/json';
$headers['Accept-Charset'] = 'utf-8';
$header = implode(PHP_EOL, array_map(function($key, $value) {
return sprintf('%s: %s', $key, $value);
}, array_keys($headers), $headers));
return json_decode(request($path, json_encode($data), strtoupper($method), $header), true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment