Get JSON data using CURL

There’s lots of communication using json, this is useful PHP function for getting JSON data using CURL function.

/*
E.g.  
  $args = '{"tid":"'.$taxonomy_id.'"}';
  $content = curl_request('http:/test.com/test.json', $args, 'POST');
*/
if (!function_exists('get_url_data_curl')) {
  function get_url_data_curl($url, $args='', $httpmethod){
    try{
      if (function_exists('curl_init') && function_exists('curl_setopt')){
      	$ch = curl_init();
      	curl_setopt($ch, CURLOPT_URL, $url);
      	curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type:application/json'));     
      	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
      	if(strcmp($httpmethod, "POST") == 0){
      		curl_setopt($ch, CURLOPT_POST, true);
      	}else{
      		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpmethod); 
      	}
      	if(strcmp($httpmethod, "POST") == 0 || strcmp($httpmethod, "PUT") == 0 && !empty($args)){
      			curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
      	}
      	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      	$result = curl_exec($ch);
      
      	curl_close($ch);
      	return $result;
      }
    }catch(Exception $e){
      $error = array(
      	'status' => 'failed',
      	'errorMessage' => $e->getMessage(),
      	'errorCode' => '500'
      );
      return json_encode($error);
    } 
  }
}

How to use is simple.

$args = '{"tid":"'.$taxonomy_id.'"}';
$content = curl_request('http:/test.com/test.json', $args, 'POST');

 

Put $args variable what you want to pass through.

Method can be either GET or POST.