How To Call API In PHP Using curl

Here we will learn about How to call API in PHP using curl.

PHP is by default compiled with cURL and it’s listed in the extensions of your phpinfo().

Here is an example,

  $data = array(
    "application_name" => "Application1",
  $apiurl     = 'https://your_domain_name/post';
  $data_array = json_encode( $data );
  $curl       = curl_init();
  curl_setopt( $curl, CURLOPT_URL, $apiurl );
  curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
  curl_setopt( $curl, CURLOPT_POSTFIELDS, $data_array );
  curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ) );
  $result = curl_exec( $curl );
  echo "<pre>";
  print_r( json_decode( $result, true ) );
  echo "</pre>";
  curl_close( $curl );

The following values of the options parameter:

  • CURLOPT_URL – curl URL to fetch.
  • CURLOPT_RETURNTRANSFERIt is the return value of curl_exec() as a string.
  • CURLOPT_POSTFIELDS – To ‘POST’ in an HTTP operation.
  • CURLOPT_HTTPHEADER – Header fields to set, in the array format like: array(‘Content-type: text/plain’, ‘Content-length: 100’)
  • CURLOPT_CERTINFO – It retrieves the modification date of the document.
  • CURLOPT_SSH_COMPRESSION – To enable built-in SSH compression.
  • CURLOPT_FILETIME – It retrieves the modification date of the document.
  • CURLOPT_HEADER – To include a header in the output.
  • CURLOPT_UPLOAD – TRUE to prepare for  upload.
  • curl_init() – This function will initialize a new session and return a cURL handle.
  • curl_setopt( $curl, option, value) – set an option for a cURL session identified by the ch parameter. The option specifies which option is to set, and value specifies the value for the given option.
  • curl_exec( $curl ) – grab URL and pass it to the variable for showing output.
  • curl_close( $curl ) – close curl resource, and free up system resources.
  • $result – The result will be displayed as JSON format.
  • json_decode( $result, false ) – When you pass false then returned objects.
  • json_decode( $result, true ) – When you pass true then objects will be converted into associative arrays.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories