I have been trying to download a file from an API in 2 different way without any success: https://example.com/export/banana/by_date/v4?api_token=666&from=$today&to=$today
*Notice the file doesn't end with .csv
, it just pop out the download
file for the file.
The file that gets downloaded is a .CSV file.
I tried using CURL:
// Date looks like this: 2016-01-31
$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_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "https://www.example.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
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)
$fp = fopen($output_filename, 'w');
fwrite($fp, $result);
fclose($fp);
- With this code I got a black test.csv file.
- I don't get anything printed on the screen after running the function (
print_r($result)
)
and I tried using file_put_contents
function:
$today = date("Y-m-d");
echo $today;
file_put_contents("", fopen("https://example.com/export/banana/by_date/v4?api_token=666&from=$today&to=$today", 'r'));
// I TRIED THIS ONE TOO:
// file_put_contents("temp.csv", "https://example.com/export/banana/by_date/v4?api_token=666&from=$today&to=$today");
*I get a CSV file with the URL inside it on the first row (https://example.com/export/banana/by_date/v4?api_token=666&from=2016-01-31&to=2016-01-31
).
Can someone help me by telling me if I am doing this right? (since this isn't a direct link to a file maybe I'm working the wrong way). And what is the right way doing this.