Skip to content

Instantly share code, notes, and snippets.

@jarontai
Created June 12, 2014 07:00
Show Gist options
  • Save jarontai/6254d08a3e985effe86d to your computer and use it in GitHub Desktop.
Save jarontai/6254d08a3e985effe86d to your computer and use it in GitHub Desktop.
php get json
// For Get
// set HTTP header
$headers = array(
'Content-Type: application/json',
);
// query string
$fields = array(
'key' => '<your_api_key>',
'format' => 'json',
'ip' => $_SERVER['REMOTE_ADDR'],
);
$url = 'http://api.ipinfodb.com/v3/ip-country?' . http_build_query($fields);
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// get the result and parse to JSON
$result_arr = json_decode($result, true);
// For post
// set HTTP header
$headers = array(
'Content-Type: application/json'
);
// set POST params
$fields = array(
'key' => '<your_api_key>',
'format' => 'json',
'ip' => $_SERVER['REMOTE_ADDR'],
);
$url = 'http://api.ipinfodb.com/v3/ip-country';
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
$result_arr = json_decode($result, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment