I am trying to export the data got from my database.
The problem is that the data comes with html codes.
I just want to export the data without html codes.
Note: My database doesn't have any html code.
$exported_db_datas (global array variable) is created like this:
while($row = mysql_fetch_array($resultset,MYSQL_ASSOC))
{
$resultsarray[$rowcount] = $row;
$exported_db_datas[$rowcount] = $row;
/*foreach($resultsarray[$rowcount] as $column)
{
$resultsarray2[$rowcount][] = $column;
}*/
$rowcount++;
}
Export codes :
$export_file = "export_phisto";
if ($format == "CSV")
{
$file = $export_file.".csv";
$separator = ",";
}
elseif ($format == "TAB")
{
$file = $export_file.".tab";
$separator = "\t";
}
elseif ($format == "TXT")
{
$file = $export_file.".txt";
$separator = "\t";
}
else// XLS
{
$file = $export_file.".xls";
$separator = "\t";
}
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Type: text/plain");
$flag = false;
foreach($exported_db_datas as $row)
{
if(!$flag)
{
// display field/column names as first row
echo implode($seperator, array_keys($row)) . "\r\n";
$flag = true;
}
echo implode($seperator, array_values($row)) . "\r\n";
}
Note: Even if I don't use print $data, exported data has html codes of the web site without data.
How can I just export the data I get from database?
Example exported data is was here.
Use strip_tags
$exported_db_datas[$rowcount] = strip_tags($row);
just use strip_tags() in this line $exported_db_datas[$rowcount] = $row; like so: $exported_db_datas[$rowcount] = strip_tags($row);
PS: don't use the mysql_* extension, it was deprecated, see the red warning box here
Related
I have code which download the excel file.
I want to save this file in folder.
if($array_count > 0)
{
$fileName = "export_data" . rand(1,100) . ".xls";
if ($error_array) {
function filterData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($error_array as $row) {
if(!$flag) {
// display column names as first row
// echo implode("\t", array_keys($row)). "\r\n";;
$flag = true;
}
// filter data
//header_remove('require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php")');
array_walk($row, 'filterData');
echo implode("\t", array_values($row)). "\r\n"; ;
}
//exit;
}
}
Please some one help me to change my code to save file in folder.
Here I have made one sample for you with static array data. We can save the file in the folder.
You can make changes in this code as per your requirement.
<?php
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$sep = "\t";
$xls = "col1".$sep."col2 \n";//Column headers
foreach ($data_array as $record){
$xls.= $record[0].$sep.$record[1]."\n"; //Append data to xls
}
$xls_handler = fopen ('xlsfile.xls','w');
fwrite ($xls_handler,$xls);
fclose ($xls_handler);
echo 'Data saved to xlsfile.xls';
?>
i am doing an ajax call and called a php page which is extracting data from a mysql table and need to convert it to excel and need to store in server folder only.
Now the problem is while doing the ajax call, its going to that php page and returning to the main page without creating the excel file.
But when i tested the php page directly then its creating the excel file and downloading it. But why its not working via ajax call.
This is my ajax call from previous page --
$.ajax({
type: "POST",
url: "admin-advertiser-details-exports.php?selectedColumns="+selectedColumns+"&excelColumn="+excelColumn,
contentType:false,
processData:false,
success:function(data){
alert('Export done');
}
});
And this is my php page which is exporting to excel --
<?php
session_start();
include 'db.php';
if(!isset($_SESSION))
{
$uname=$_SESSION['uname'];
}
else if(empty($_SESSION['uname']))
{
header('Location: index.php',TRUE);
}
$UserName = $_SESSION['uname'];
$UserID = $_SESSION['uid'];
$UserType = $_SESSION['utype'];
$selectedColumns = $_GET['selectedColumns'];
$excelColumn = $_GET['excelColumn'];
$array = explode('\t',$excelColumn);
$sql = "select ".$selectedColumns." from advertisers_details ad join user_details ud on ad.adv_manager=ud.user_id order by ad.adv_id asc";
$setRec = mysqli_query($linkID1, $sql);
$columnHeader = '';
foreach ($array as $value) {
$value = '"' . $value . '"' . "\t";
$columnHeader .= $value;
}
$setData = '';
while ($rec = mysqli_fetch_row($setRec))
{
$rowData = '';
foreach ($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=advertiser_detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
If i am running this php page directly the i am getting the excel file, but via ajax call its not working.
Hope this example work best for you.
I have used window.open and set url of target file with parameter.
JS code used
/* Export Orders */
$(document).on('click','#btn_export_delivery_order',function(){
var first_input = $('#name_email_order_search').val();
var date_range = $('#reportrangeorder').val();
var order_status = $('#order_status').val();
window.open("ajax_responce.php?method_name=export_orders&shop="+ shop+"&first_input=" + first_input + "&date_range=" + date_range + "&order_status=" + order_status + "", '_blank');
});
Code used in ajax_response.php
public function export_orders(){
ob_start();
if (isset($_GET['shop']) && $_GET['shop'] != '') {
$export = array();
$export_data = array();
$shopinfo = $this->get_settings($_GET['shop']);
$store_client_id = $shopinfo['store_client_id'];
$date_format = $shopinfo['date_format_first'];
$options_arr = array("skip" => 0, "limit" => 99999);
$where = $this->where_to_clause_export_search($store_client_id, $_GET);
$fullfilment_status_array = array('Unfulfilled','Fullfill','Partially fullfill','Cancelled');
$export_result = $this->select_result(TABLE_ORDERS, '*', $where, $options_arr);
foreach($export_result['data'] as $row){
$export['Name'] = $row['order_name'];
$export['Billing Name'] = $row['first_name'] . ' ' . $row['last_name'];
$export['Email'] = $row['email'];
$export['Fulfillment Status'] = $fullfilment_status_array[$row['status']];
$export['Total'] = $row['total'];
$export['Created at'] = date($date_format, strtotime($row['created_at']));
$export['Delivery Status'] = $row['delivery_status'] == 0 ? 'Pending' : 'Delivered';
$export['Delivery Date'] = date($date_format, strtotime($row['delivery_date']));
$export['Delivery Time'] = (isset($row['delivery_time']) && $row['delivery_time'] != '') ? $row['delivery_time'] : '-';
$export_data[] = $export;
}
/* Export Data */
$filename = "orders_export.csv";
$f = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
$outputdata = $export_data;
$firstLineKeys = false;
foreach ($outputdata as $row) {
if (empty($firstLineKeys)) {
$firstLineKeys = array_keys($row);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
fputcsv($f, $row);
}
fclose($f);
ob_end_flush();
exit();
}
}
This code is tested well and working fine.
I have a website that I created for reports. There are basically 3 reports. I have a button on each page that calls another PHP page that will download the results of the query that fills the page into a CSV file. This works fine on one page, but on the other two it gives me an error when trying to open. It says:
The file format and extension of 'FileName' don't match. the file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I click yes, then get this:
Excel has detected that 'FileName' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Click OK to try to open the file in a different format.
I click OK and it opens fine.
Where as on the other page it just opens.
Here's most of the ExportToExcel.php
switch ($_POST['ExportToExcel'])
{
case "QDef":
$tsql = "select Id,QSrc,QName,QDef,isActive,RunReport,FilePath from pmdb.v_QDefs order by Id";
$hsql = "select Headings from TableHeadings where TableName = 'v_QDefs' and Headings != 'Edit' order by ID";
break;
case "TableUpdates":
$tsql = "select ID, TableName, UpdateDate from pmdb.TableUpdates order by UpdateDate";
$hsql = "select Headings from TableHeadings where TableName = 'TableUpdates' and Headings != 'Edit' order by ID";
break;
}
$filename = $_POST['ExportToExcel'];
header("Content-Type: application/x-csv");
header("Content-Disposition: attachment; filename=$filename.csv");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
//end of printing column names
echo $br; //separate the headers and the data
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}
I have a include at the top that has the connection string for connecting to my MSSQL DB, which does work, or there'd be nothing displayed on the page to begin with.
I just con't figure out why the page doesn't work the same way for all reports when they are all calling the page the same way.
EDIT again
I tried several ideas from below and now I have this:
$filename = $_POST['ExportToExcel'] . '.csv';
$Opened = fopen($filename,'w');
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
fputcsv($Opened,$headings);
foreach($conn->query($tsql) as $row)
{
fputcsv($Opened,$row);
}
fclose($Opened);
Which still gives me a blank spreadsheet. So obviously I'm still doing something wrong?
Nevermind, I updated the Headings for all the tables that I am trying to export so that the first column is no longer ID, but is instead Id. Since it's no longer all caps it is working fine without the fputcsv since that isn't doing anything for me anyhow.
$filename = $_POST['ExportToExcel'] . '.csv';
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}
I have to create a excel file having near about 350 columns and 1000 rows. I have developed code for this task using PHPExcel. But it takes 42secs to create file. So I have to create excel file without PHPExcel. So I have developed a script in which data is identified by "\t" for different tab data. It takes just 2secs to create file. But problem is that when I'm going to open that file (created by using "\t"), message of corrupted file is displayed. And on repairing that file, it works fine. But I can't understand that where I'm making mistake in script. If anyone can solve this problem either by using PHPExcel (less execution time) or by solving error of corrupt file, then answer will be appreciated. Here is my code (CakePHP 3).
Input Array like
// Do not confuse with { instead of [. It's okey.
// $export_data and $data both are same (Input array).
{
"0": {
"customer_id": 1,
"name": "John Stevens",
"Date of 1 Purchase": "2014-08-05T00:00:00+0000",
"Date of 2 Purchase": "2014-09-05T00:00:00+0000",
"Date of 3 Purchase": "2014-10-05T00:00:00+0000",
...
...
... 350 Cols ...
}
"1": {
...
}
...
...
"999 Rows"
}
Using PHPExcel
$r = 1;
$filename = FILE_PATH . 'galliyan.xlsx';
$header = array_keys($export_data[0]);
$objPHPExcel = new \PHPExcel();
$col = 0;
foreach ($header as $field) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
chmod($filename, 0777);
$r++;
$objPHPExcel = \PHPExcel_IOFactory::load($filename);
foreach($export_data as $row) {
$col = 0;
foreach ($row as $ro) {
$objPHPExcel->getActiveSheet()->setCellvalueByColumnAndRow($col, $r, $ro);
$col++;
}
$r++;
}
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
chmod($filename, 0777);
EDIT (UPDATED CODE)
$filename = FILE_PATH . 'galliyan.xlsx';
$header = array_keys($export_data[0]);
$objPHPExcel = new \PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$col = 0;
foreach ($header as $field) {
$sheet->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}
$objPHPExcel->getActiveSheet()->fromArray($export_data, null, 'A2');
$writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$writer->save($filename);
chmod($filename, 0777);
Using "\t"
foreach ($data as $row) {
if (!$flag) {
$header = array();
// display field/column names as first row
$header = array_keys($row);
$header = $this->setExcelHeaders($header);
$this->createExcelFile($dir_name, $filename, $header, $export_type);
$flag = TRUE;
}
array_walk($row, array($this, 'cleanData'));
array_push($values, $row);
}
$values = $this->setValues($values);
$this->writeExcelFile($dir_name, $filename, $values);
function setExcelHeaders($hdrs) {
$header = '';
foreach ($hdrs as $title_val) {
$header .= $title_val . "\t";
}
return $header;
}
function createExcelFile($dir_name, $filename, $header, $export_type = '') {
$fp = fopen($dir_name . "/" . $filename, 'w');
fwrite($fp, "$header\n");
fclose($fp);
$permission = Configure::read('Config.PERMISSION');
if ($export_type == "") {
chmod($dir_name, $permission);
}
chmod($dir_name . "/" . $filename, $permission);
}
public function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
private function setValues($all_vals) {
$data = '';
for ($i = 0; $i < count($all_vals); $i++) {
$line = '';
foreach ($all_vals[$i] as $value) {
if ((!isset($value)) || ( $value == "")) {
$value = "\t";
}
else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
return $values = str_replace("\r", "", $data);
}
function writeExcelFile($dir_name, $filename, $data) {
$fp = fopen($dir_name . "/" . $filename, 'a');
fwrite($fp, "$data");
fclose($fp);
}
As you mentioned "without PHPExcel", have you tried looking at alternatives that can be faster than PHPExcel? For instance, you can generate a 350x1000 XLSX spreadsheet with Spout (https://github.com/box/spout) in just a few seconds.
Generating a CSV file is also a good alternative and I'd recommend you going this route if you can. The export process will be way faster! But don't try to reinvent the wheel, there a already a lot of CSV writer out there, ready to use (Spout and PHPExcel both have one for instance).
I have a code that converts mysql table to excel sheet. It converts and the excel sheet is downloaded but whenever I try to open the file it gives an error msg in excel 2007:"The file you are trying to open is in a different format than specified by the extension...".The excel sheet opens after I click on 'Yes' but it is nothing but a white blank sheet.I have seen the similar posts but none of them solves my problem...Please help...Thank you
<?php
include('dbcon.php');
?>
<?php
$sql = "SELECT * FROM stu_gen_info";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-Type: application/vnd.ms-excel");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
?>
try adding this
header("Content-Type: application/vnd.ms-excel");