Skip to content

Instantly share code, notes, and snippets.

@albasyir
Last active April 23, 2020 13:34
Show Gist options
  • Save albasyir/e84a4fe7038a5000d5392d336055f825 to your computer and use it in GitHub Desktop.
Save albasyir/e84a4fe7038a5000d5392d336055f825 to your computer and use it in GitHub Desktop.
Mini http client for php
<?php
/**
* Kelas HTTP
* untuk narik data
*/
class Http {
/**
* Tempat endpoint
*/
public $endpoint;
/**
* Membuat object http, disarankan pakai endpoint biar mudah
*
* @param string $endpoint
* @return void
*/
public function __construct($endpoint = "")
{
$this->endpoint = $endpoint;
}
/**
* Get dari http
*
* @param string $url
* @return array
*/
public function get($url){
$content = file_get_contents($this->endpoint . $url);
// coba convert dari json ke object
$json = json_decode($content, true);
// returnnya jika memang json maka json yg di kasih
// kalo enggak berarti kontent mentah langung yg di kasih
return (json_last_error() === JSON_ERROR_NONE) ? $json : $content;
}
}
require_once('./Http.php');
$http = new Http("https://api.kawalcorona.com/");
// langsung jadi array php
$data1 = $http->get("/");
// langsung jadi array php
$data2 = $http->get("/indonesia/provinsi/");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment