Get JSON data using CURL

Spread the love

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

  $args = '{"tid":"'.$taxonomy_id.'"}';
  $content = curl_request('http:/', $args, 'POST');
if (!function_exists('get_url_data_curl')) {
  function get_url_data_curl($url, $args='', $httpmethod){
      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);
      		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);
      	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:/', $args, 'POST');


Put $args variable what you want to pass through.

Method can be either GET or POST.

Facebook Comments

Published by

Titus Choi

I love technology. Working for information technology. Interested in AVR technology. Playing with RC stuff.