Home » Php » php – how to hit the API by using CURL?

php – how to hit the API by using CURL?

Posted by: admin February 25, 2020 Leave a comment

Questions:

i try to hit the API by using curl
in this case i try to hit : https://jsonplaceholder.typicode.com/posts

  <?php

class process extends CI_Controller {


    $headers = 'Content-Type:application/json';



    $process = curl_init('https://jsonplaceholder.typicode.com/users'); //your API url
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($process, CURLOPT_HEADER, 1);
    curl_setopt($process, CURLOPT_TIMEOUT, 20);
    curl_setopt($process, CURLOPT_POST, 1);

    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
    $return = curl_exec($process);
    curl_close($process);

    //finally print your API response
    print_r($return);

}

but it shows some errors like this

An uncaught Exception was encountered Type: ParseError

Message: syntax error, unexpected ‘$headers’ (T_VARIABLE), expecting
function (T_FUNCTION) or const (T_CONST)

Filename: E:\XAMPP\htdocs\Crudview\application\controllers\process.php

Line Number: 6

Backtrace:

File: E:\XAMPP\htdocs\Crudview\index.php Line: 315 Function:
require_once

How to&Answers:

Please use like that:-

<?php

class process extends CI_Controller {

    function curlAPI(){
        $headers = 'Content-Type:application/json';
        $process = curl_init('https://jsonplaceholder.typicode.com/users'); //your API url
        curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($process, CURLOPT_HEADER, 1);
        curl_setopt($process, CURLOPT_TIMEOUT, 20);
        curl_setopt($process, CURLOPT_POST, 1);

        curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
        $return = curl_exec($process);
        curl_close($process);
        print_r($return);
    }
}

?>