Download CSV file in jquery mobile framewrok with zend - php

I am doing project with jquery mobile framework using zend framework.I have the page to download report in csv format. I can downloaded it from desktop version. But the same page in mobile version runs in ajax due to jquery mobile result undefined with blank page.
for example, i call this http://www.test.com/report/downloadtransaction when i click download button. This calls downloadtransactionAction in reportcontroller ,then finally gives csv file.
Call is happening in mobile version but not able to see download file window.
Below is the code
public function downloadtransactionAction(){
$preview_result = getmySessionData('preview_result')->preview_key;
//print_obj($preview_result);
$myFile = "TRANSACTION_" . time() . ".csv";
header("Content-Disposition: attachment; filename=\"$myFile\"");
header("Content-Type: application/vnd.ms-excel; charset=UTF-16LE");
$out = fopen("php://output", 'w');
//$csvData = array('Warehouse Id', 'Name','Item No','Minimun Stock','Current Stock');
$csvData = array('No','DATE','USER', 'TRADE TYPE','AMOUNT');
$o = fputcsv($out, $csvData, ',', '"');
$count = 1;;
foreach($preview_result as $key => $value)
{
$csvData = array();
$csvData = array($count,date('Y/m/d',strtotime($value['date'])),$value['current_admin_name'],($value['trade_type'])?'WithDraw' : 'Deposit',$value['amount']);
$o = fputcsv($out, $csvData, ',', '"');
$count++;
}
fclose($fh);
// DOWNLOAD CSV
echo $out;
die;
}
I need to download csv in mobile version as like in desktop version
What i done wrong on this ?

I use the below code to disable the ajax in jquery mobile framework,
<script type="text/javascript">
// do not handle links via ajax by default
$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; });
</script>
This will disable the ajax in page and make redirecting to clicked page.

Related

Echoing to screen when using headers to output to csv

I have a PHP application which generates a set of codes , saves them to MySQL DB and then outputs the same to the user as a downloadable csv file. I also have an echo statement after the code block to convert the PHP array to csv. The echo statement after the convert_to_csv function call instead of outputting to the browser outputs to the file instead and overwrites the first line. How do I get the echo statement to output to the browser instead? The code block is below:
convert_to_csv($newCodesArray,$fileName,',');
echo "Your file was successfully generated";
function convert_to_csv($input_array, $fileName, $delimiter)
{
header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=\"$fileName\"");
$f = fopen('php://output', 'w');
/* loop through array */
foreach ($input_array as $line) {
/* default php csv handler */
fputcsv($f, $line, $delimiter);
}
fclose($f) or die("Can't close php://output");
}
You have already defined the header as text/csv. So it wont print in the browser as it requires text/html.
Alternatively you can do as following. Copy your function to different file (Ex. csv.php).
<?php
echo "Your file was successfully generated <script> window.location = 'csv.php' </script>";
Now it will print your echo string and start download your csv file.
As Magnus Eriksson commented,
Above code does not checking its really generated successfully or not. We can extend code with AJAX.
<script>
$.ajax('csv.php', {
success: function(data) {
document.write('Your file was successfully generated.');
windows.location = 'csv.php';
},
error: function() {
document.write('Your file generation failed.');
}
});
</script>
Note:- AJAX call will generate file two times.

Converting Table to CSV

I'm using str_get_html http://simplehtmldom.sourceforge.net/ to export an HTML table to CSV. The user completes a form and the same table displays on screen. If they check a form box, I would like it to also generate a CSV file for download (in addition to displaying the table on screen).
Using ajax, I have the table being displayed in an empty div element.
<script type="text/javascript">
$(document).ready(function() {
var options = {target: '#output1'};
$('#completed').ajaxForm(options);});
</script>
It's almost working. The only problem is that it displays the CSV content in the div update, rather than generating a file for download. If I remove the on-screen display of the table and remove the ajax functionality, it generates the CSV file perfectly. Can someone help me with the code below so that it will generate a file for download?
include 'simple_html_dom.php';
$html = str_get_html($table);
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
foreach($html->find('tr') as $element)
{
$td = array();
foreach( $element->find('th') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
$td = array();
foreach( $element->find('td') as $row)
{
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
Instead of using "php://output", you need to use a path/filename. Right now, you are telling php to write to the output buffer mechanism.
For example:
$fp = fopen("path/to/filename.csv", "w");

Can I initiate an automatic download of a csv and display text on a page at the same time?

I'm imagining a user going to page and having a download automatically initiate. The page they visit will have instructions on what to do with the file. Right now, the text of the page is being included in the csv file instead of echoing to the page. Can this even be down in one script? Here is my code...
<?php
function databaseConnection() {
$conn = new PDO("sqlsrv:server=IP ; Database=database",'user','password');
return $conn;
}
function getStudents() {
global $conn;
$studentsql =
"SQL query";
$studentquery = $conn->prepare($studentsql);
$studentquery->execute();
$studentarray = array();
while ($studentrow = $studentquery->fetch(PDO::FETCH_ASSOC)) {
$studentarray[] = $studentrow;
}
return $studentarray;
}
function createFile($fileheader,$filebody) {
$file = fopen('php://memory', 'w');
fputcsv($file, $fileheader);
foreach ($filebody as $key => $students) {
fputcsv($file, $students);
}
rewind($file);
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
fpassthru($file);
fclose($file);
}
$conn = databaseConnection();
$fileheader = array("header1","header2");
createFile($fileheader, getStudents());
$conn = null;
echo "<p>The file has automatically downloaded and was placed in your downloads folder.</p>
<p>Double clicking the file will automatically open it in Excel. You should then go to File | Save As <br>
and choose a different name and save it as an excel file by choosing .xlsx as the file type.";
?>
You have two options:
Display the result on the page and then redirect to the file download.
Use Javascript, load the data through an AJAX request, display it on the page and redirect to a data URI.

Downloaded .csv file contains HTML tags as text

I want to download a .csv file through link.For that a Download link is defined in a template file.
To generate .csv file I have written a piece of code as follows.
public function loadPartnerApplicantData() {
$inboundBo = BoFactory::getInboundHttpRequestBo();
$fileType = $inboundBo->getSanitizedGetParam('f');
$formId = $inboundBo->getSanitizedGetParam('fid');
ServiceFactory::getFormService()->loadFormDetails($formId);
$dbTable = BoFactory::getFormBo()->getFormDbTable($formId);
$formName = slugify(BoFactory::getFormBo()->getFormName());
$fileName = $formName . "." . time();
$fieldMasterSqlQuery = "SELECT field_name,field_label FROM" . FORM_FIELDS_MASTER_v2 . "where form_id='$formId' order by serial_no";
$fieldMasterSqlQueryStatus = mysql_query(mysql_fetch_assoc($fieldMasterSqlQuery));
$csvHeader = "";
$fieldNameArray = array();
foreach ($fieldMasterSqlQueryStatus as $key => $value) {
if ($value['field_name'] == 'declaration' || $value['field_name'] == 'docPicture') {
continue;
}
$csvHeader.= "\"{$value['field_label']}\";";
$fieldNameArray[] = $value['field_name'];
}
$queryString = implode(",", $fieldNameArray);
$dbTableSqlQuery = "SELECT $queryString FROM `$dbTable`";
$dbTableSqlQueryStaus = mysql_query(mysql_fetch_assoc($dbTableSqlQuery));
ef_clearBuffer();
// To generate csv
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$fileName.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo($csvHeader);
foreach ($dbTableSqlQueryStaus as $applicantData) {
echo "\n";
foreach ($fieldNameArray as $fieldName) {
echo "\"$applicantData[$fieldName]\";";
}
echo "\n";
}
}
And the required .csv is generated .
But at the end of .csv file HTML tags of the browser is getting displayed. which should not be there.
Please suggest me to remove the html content from the generated .csv file.
Thanks in advance.
Since your function handles the request till the end (i.e., delivers all data), and you don't want the framework (whichever you're using) to continue processing, add
exit(0);
as last line of your function. That will halt the processing after the content is delivered and prevent the framework/environment from sending additional data.
Maybe you already had some echo commands before the header manipulation, then the .csv file which you want to download will contains all strings you have written before.

exporting a csv file in PHP and JavaScript

I'm trying to implement a tool to export data from a research website as a csv file. In my download controller, I have:
public function export(){
$data = array(
array('Name', 'Age', 'City'),
array('Philippe', '23', 'Palo Alto'),
array('John', '30', 'San Francisco'),
array('Paul', '20', 'Los Angeles')
);
header('Content-type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$fp = fopen('php://output', 'w');
foreach( $data as $line ) {
fputcsv( $fp, $line );
}
fclose($fp);
}
and from my view, I do:
function download() {
$('#download').empty().html('<img src="<?php echo base_url();?>/images/loader.gif" />');
$.post('<?php echo base_url();?>/index.php/download/export');
}
and download() is fired up when the user click to a button with a onclick='download()'.
However, I'm not seen the file being downloaded, nor a error message. When I look into my firebug console, I see:
200 OK 29ms jquery.min.js (line 4) HeadersPostResponseCookies
Name,Age,City Philippe,23,"Palo Alto" John,30,"San Francisco"
Paul,20,"Los Angeles"
What am I missing?
Thanks
You don't actually want an AJAX request here. You want to redirect your user to the file with:
window.location = '<?php echo base_url();?>/index.php/download/export';
The AJAX request is telling the server to send the data back to the script's success method. Since it's a download, the redirect won't make you leave the page so you can use this method without confusing your user.

Categories