Generate a CSV file from XML stream for MYSQL Import - php

I am trying to get data from a online XML file and save in CSV format. I was able to save the CSV file but the data is not saved properly as a comma separated CSV and due to which the data has no delimiter and is not getting imported in mysql properly. It imports in mysql in one column itself where there are 8 columns and it should be imported in different columns as per CSV data.
I am using
$report = stream_get_contents($request->getReport());
// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="data.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('data.csv','w+');
fwrite($file,$report);
fclose($file);

You are writing the lines without formatting them properly first. You should use fputcsv instead of fwrite.

Related

fputcsv displaying data in browser instead of downloading data as CSV file

I am using fputcsv function to export data as CSV file but it is displaying all data in browser instead of downloading this as CSV file. Here is my code
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen('php://output', 'w');
fputcsv($output, $column_headings);
fclose($output);
Data is displaying correctly in browser but I want to download this as export.csv file.I do not know what is wrong with this. Any suggestion regarding this will be appreciated.
You cannot control how the browser handles the text/csv content type, however, you can tell the browser it should treat the data as binary.
header('Content-Type: application/octet-stream');
I added ob_start(); at the start of my file and now I can export files.

Export html table contents as xlsx format

Iam using PHP+jQuery to export the html table contents. When I click on on export button, the excel file is generated successfully as xls format. I want to generate the file as xlsx format.
$FileName="my-file.xls";
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename='.$FileName.'');
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['tableData'];
exit();
Adding the jQuery
var clone_val = $(".tblExport").clone();
$("#tData").val($('<span><style> .textFormat { mso-number-format:"\#"; } .numberFormat { mso-number-format:"0\.00" }</style>').append (clone_val).html());
$("#excel-export-form").submit();
The table contents is stored inside a input box having attribute id="tData" name="tableData" using jQuery.
When I changed the filename as my-file.xlsx, a corrupted xlsx file is generated. Also tried Data Table excel export, but it didn't support multiple headers.
You can do this with a php library. I prefer PhpSpreadsheet to use for working with excel.

PHP Output MS SQL to a downloadable CSV or Excel file

I'm trying to output data returned by an MS SQL query to an Excel or CSV file with PHP.
I've used the script in this answer and can output the file OK. Without the header lines (at the bottom of my code) it saves in my server's folder structure rather than outputs as a download to the browser.
If I add the header lines, it ouputs to a CSV file but writes the page's HTML to the file rather than the extract from the database! Am I missing a setting somewhere? I tried running the code on a page with no HTML in it (PHP and SQL code only), but it still happens.
// Give the file a suitable name:
$FileName= $PartNumber.".csv";
$fp = fopen($FileName, 'w');
// Connect to MS SQL server; the actual database is chosen in the form
// ConnSQL defined in inc/dbconn/config.php
ConnSQL($idDatabase);
// the query is a biggie; here it is:
require 'inc_sql.php';
// run it through the SQL server
$rstBOM = sqlsrv_query($GLOBALS['ConnSQL'], $sqlBOM);
while ($export= sqlsrv_fetch_array($rstBOM, SQLSRV_FETCH_ASSOC)) {
if (!isset($headings))
{
$headings = array_keys($export);
fputcsv($fp, $headings, ',', '"');
}
fputcsv($fp, $export, ',', '"');
}
// force download csv - exports HTML to CSV!
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="'.$FileName.'"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ". filesize($FileName));
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="'.$FileName.'"');
fclose($fp);
Any ideas where I'm going wrong please?
You need to output your csv file to the browser simply by putting
readfile($FileName);
At the end of your code after the fclose($fp); function.
Otherwise, browser receives the headers for files, but no content in sent from your PHP code.
You could also generate your csv file on the fly and just echo $csvFileContents; instead. This would prevent server from creating and writing data to file, which could lead to security breaches.
Good luck!

Generate 3 CSV files from 1

I have one CSV file. From which i want to create 3 different CSV file which diff name , headers and data.
Lets suppose i have data.csv with headers (data1,data2,data3,data4).
Now i want to create 2 different CSV based on data.csv. Both may name "data-next.csv" & "data-next-next.csv".
When i am trying to set html headers (for assigning name) then its only setting for onetime.
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="data.csv"');
Is there any other way around.

Return string rather than database entry in CSV export using csv_from_result

I am using codeigniter to produce a CSV from a database entry. The following code works
$this->load->dbutil();
$csv = $this->dbutil->csv_from_result($stories);
echo $csv;
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $csv);
fclose($fp);
However, I have two questions.
1) Why does my code rely on echoing $CSV? It returns a blank cvs if I comment out this line.
2) How do I take the $CSV variable and edit it. At the moment my database stores some information as integers that the controllers turn to strings in the normal running of the site i.e. I might store the priority in the database as 0,1,2 but in the view I show Urgent,high,low. I would like to show these strings in the exported CSV rather than the database entry. I am a bit confused as to how I do this. I was thinking of a loop with a switch statement but I dont really know how to interact with the $CSV variable - Or should I be doing this in the model where the data is still in an object rather than csv_from_result()
1) $csv contains all the information, it is all the content that makes up your file. That's why if you don't echo it out you just get a blank CSV file.
2) You don't want to edit $csv, that variable contains everything ready to go. You want to edit $stories, which from the looks of what you have pasted above contains everything from your database that then gets converted into CSV by $this->dbutil->csv_from_result. Look through your code and find where $stories is loaded, then modify that.

Categories