How to Create and Download a CSV File from PHP Script

How to create and download a csv file from php script?

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line);
}

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: text/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}

And you can use it like this:

array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);

Update:

Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');

// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');

foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}

How to download CSV file from PHP script via AJAX?

Further to my comment(s), I would make the form able to submit normally or using ajax. Ajax for search, normal submit for download:

<div class="container">
<!-- Make this a proper form tag again -->
<form id="ldap-form" method="post" action="working_csv.php">
<h2><strong><p>Search the LDAP server</p></strong></h2>
<label for="location"><p>Enter your search location (ex: dc=example,dc=com)</p></label>
<input type="text" id="location" name="location" placeholder="Search Location.." />
<label for="filter"><p>Enter your search filter(s) (ex: uid=* or </p></label>
<input type="text" id="filter" name="filter" placeholder="Filter(s).." />
<input type="submit" name="search" id="search" value="Search LDAP Server" />
<input type="submit" name="download" id="download" value="Download results as CSV file" />
</form>
<!-- Response container -->
<p id="msg"></p>
</div>

<script>
$(function(){
$('input[type="submit"]').on('click', function(e){
// Stop form from submission
e.preventDefault();
// Detect button press type
let thisSubmission = $(this).attr('name');
// If the button is search, do ajax
if(thisSubmission == 'search') {
$.ajax({
type: "post",
url: $('#ldap-form').attr('action'),
data: $('#ldap-form').serialize(),
cache: false,
success: function(html){
$('#msg').html(html);
}
});
}
else {
// Just submit the form normally
$('#ldap-form').submit();
}
});
});
</script>

Download file as csv when running script from command line

You can update the line as follows, where $$filepath is the file path name.

$fp = fopen($$filepath, "w");

download a csv file dynamically create in PHP

Here you go, compliments of Dagon and myself.

<?php

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$data = array(
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('aaa', 'bbb')
);

outputCSV($data);

function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}

script to regularly download a csv file from a webpage that uses php

This website sends an ajax POST request to http://www.meteo.fvg.it/ajax/getStationData.php with the following formfields:

a: 2018
m: 8
g: 4
s: CMT@Camino@syn@45.920300@12.938600@30
t: H_2
ln:
o: visualizza

and returns a html page, where the downloadable CSV data is weirdly encoded directly into the href attribute of the download button:

<a href=\"data:application\/csv;charset=utf-8,giorno%3Bora%20UTC%2A%3BPioggia%20mm%3BTemp.%20gradi%20C%3BUmidita%27%20%25%3BVento%20med%20km%2...">

So in order to solve that programmatically, you have to check out the network tab in Chrome Dev Tools and get familiar with the fields and their params, that get sent along with the ajax request.
Then use curl to grab the result, like this (just copied out of the network tab) Info

curl 'http://www.meteo.fvg.it/ajax/getStationData.php' -H 'Cookie: PHPSESSID=olng2rqoia3qsecangkh3bg4r4' -H 'Origin: http://www.meteo.fvg.it' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9,de;q=0.8' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.23 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Referer: http://www.meteo.fvg.it/archivio.php?ln=&p=dati' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' -H 'DNT: 1' --data 'a=2018&m=8&g=4&s=CMT%40Camino%40syn%4045.920300%4012.938600%4030&t=H_2&ln=&o=visualizza' --compressed

and then parse the result with a dom parser, to grab the content of the download button

and then url_decode that and save it.

You could use php, python, node.js for that - what ever you are more familiar with.

maybe, if you snoop around a bit more, you'll find a static url that gives you the result directly.



Related Topics



Leave a reply



Submit