Downloading a CSV file using PHP from an API - with a URL that doesn't end with .csv Downloading a CSV file using PHP from an API - with a URL that doesn't end with .csv curl curl

Downloading a CSV file using PHP from an API - with a URL that doesn't end with .csv


The target url is https so perhaps you need to add certain ssl specific options

curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );curl_setopt( $ch, CURLOPT_CAINFO, realpath( '/path/to/cacert.pem' ) );

another common cause of curl requests failing is the lack of a useragent string.

curl_setopt( $ch, CURLOPT_USERAGENT, 'my useragent string' );

You can set similar options when using file_get_contents by setting options for the $context

Based on your last comment, add:

 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );


This is well known (for me) problem with accesing https resources with cURL from php - it can't verify certificate in default configuration. So easiest thing to get this script works, you should add two additional lines for curl_config:

$today = date("Y-m-d");$output_filename = "test.csv";$host = "https://example.com/export/banana/by_date/v4?api_token=666&from=$today&to=$today";$ch = curl_init();$curl_config = [    CURLOPT_URL => $host,    CURLOPT_VERBOSE => 1,    CURLOPT_RETURNTRANSFER => 1,    CURLOPT_AUTOREFERER => false,    CURLOPT_REFERER => "https://www.example.com",    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,    CURLOPT_HEADER => 0,    CURLOPT_SSL_VERIFYHOST => 0, //do not verify that host matches one in certifica    CURLOPT_SSL_VERIFYPEER => 0, //do not verify certificate's meta];curl_setopt_array($ch, $curl_config); //apply config$result = curl_exec($ch);if (empty($result)){    echo  curl_error($ch); //show possible error if answer if empty and exit script    exit;}curl_close($ch);print_r($result); // prints the contents of the collected file before writing..// the following lines write the contents to a file in the same directory (provided permissions etc)file_put_contents($output_filename, $result);