Forum

Thread tagged as: Question, Forms

Form App - Download CSV

I'm using the Form App in Perch and have a requirement to make a CSV file available outside of the Perch admin interface.

I think it may be possible to generate a CSV file of all of the form data using a template but I would very much appreciate a pointer on how this might be accomplished in practice.

William File

William File 0 points

  • 6 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

If you log in and look at the form responses, there's a button to download a CSV.

In this instance I need to give a third party access for audit purposes and this access cannot be via the Perch admin interface, it needs to be outside of that via a URL.

Drew McLellan

Drew McLellan 2638 points
Perch Support

That's not possible with the app as it stands.

How would you plan to authenticate it?

I realise that the app doesn't include that functionality but had seen a response from you to another question where the possibility of using a template to generate a CSV file was put forward.

Possibly authenticate via username & password set in htaccess file.

Drew McLellan

Drew McLellan 2638 points
Perch Support

You can't output that information via a template.

OK, understood, that's a non starter.

Any suggestions / advice as to how to go about generating a CSV file from the Forms app stored data?

Drew McLellan

Drew McLellan 2638 points
Perch Support

It would be simple to do, but you'd need to write some PHP to do it.

Is the following a valid basis to achieve SQL to CSV output or is there anything unique to Perch that I may need to know?

<?php
$host = 'localhost';
$user = 'userName';
$pass = 'password';
$db = 'databaseName';
$table = 'tableName';
$file = 'export';
 
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
 
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
if (mysql_num_rows($result) > 0) {
 while ($row = mysql_fetch_assoc($result)) {
  $csv_output .= $row['Field'].", ";
  $i++;
 }
}
$csv_output .= "\n";
 
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
 for ($j=0;$j<$i;$j++) {
  $csv_output .= $rowr[$j].", ";
 }
 $csv_output .= "\n";
}
 
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
Drew McLellan

Drew McLellan 2638 points
Perch Support

That code is using the old mysql extension which is no longer valid in modern PHP. Also you'll need to decode the form contents, which is stored as JSON.