简体   繁体   中英

how to hit the API by using CURL?

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

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);
    }
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM