PHP - Need Help For Exporting Scriprt To Csv
Hello, guys i got some issue in my script for exporting data to CSV (exel for view)
Its export all data in one collumn, but i need to export each data in separeta column like. a B a1 ID ID2 But i got there this: a B a1 ID""ID2 Here is the script: Code: [Select] <?php class WDealAdminExport extends UWidgetWorklet { public function accessRules() { return array( array('allow', 'roles' => array('company')), array('deny', 'users'=>array('*')) ); } public function taskConfig() { $list = wm()->get('deal.admin.coupon'); $_GET[$list->modelClassName] = $_POST[$list->modelClassName]; $list->init(); $dataProvider = $list->dataProvider(); $dataProvider->pagination = false; $csv = array( array( $this->t('ID'), $this->t('Order ID'), $this->t('Deal ID'), $this->t('User'), $this->t('Status'), ) ); foreach($dataProvider->data as $data) { $row = array( "#".$data->couponId(), $data->orderId, $data->dealId, $data->user->email." [".$data->user->getName(true)."]", $data->status==1 ? ($data->deal->isExpired() ? $this->t('Expired') : $this->t('Available')) : $this->t('Used') ); if($_POST['charset'] != 'utf-8') { $row[3] = iconv('utf-8', $_POST['charset'], $row[3]); $row[4] = iconv('utf-8', $_POST['charset'], $row[4]); } $csv[] = $row; } $contents = $this->generateCSV($csv); $this->send($contents); } public function taskGenerateCSV($src) { $csv = ''; foreach($src as $row) { foreach($row as $item) $csv.= $this->escape($item).$this->param('delimiter'); $csv = rtrim($csv,$this->param('delimiter'))."\r\n"; } return $csv; } public function taskEscape($value) { return '"'.str_replace('"','""',$value).'"'; } public function taskSend($contents) { $content_type = "application/octet-stream"; $filename = 'export.csv'; // disable browser caching header('Cache-control: private'); header('Pragma: private'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-Type: '.$content_type); header('Content-Transfer-Encoding: binary'); header('Content-Length: '.strlen($contents)); header('Content-Disposition: attachment;filename="'.$filename.'"'); echo $contents; app()->end(); } } Similar TutorialsHello,
I created a web page that executes request from mysql and prints it on web page. I also created a export submit button to export mysql query in csv format file. When I select values and then click on export buttons, I get nothing and page gets refreshed.
Here is the link of my site: rahil.me/index.php
Here is the code:
These are the buttons:
<input type="submit" name="search" value="Search"> <input type="submit" name="export" value="Export" />PHP code: if (isset($_POST['export'])) { if (empty($_POST['service'])) { echo "Please select service in dropdown" . "</br>"; } else { $service = $_POST['service']; } if (empty($_POST['environment'])) { echo "Please select Environment in dropdown" . "</br>"; } else { $env = $_POST['environment']; } if ((!empty($service)) && (!empty($env))) { $sql="SQLQUERY REMOVE"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = mysqli_query($con,$sql); /* * send response headers to the browser * following headers instruct the browser to treat the data as a csv file called export.csv */ header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=export.csv'); /* * output header row (if atleast one row exists) */ $row = mysqli_fetch_assoc($result); if ($row) { echocsv(array_keys($row)); } /* * output data rows (if atleast one row exists) */ while ($row) { echocsv($row); $row = mysqli_fetch_assoc($result); } /* * echo the input array as csv data maintaining consistency with most CSV implementations * - uses double-quotes as enclosure when necessary * - uses double double-quotes to escape double-quotes * - uses CRLF as a line separator */ function echocsv($fields) { $separator = ''; foreach ($fields as $field) { if (preg_match('/\\r|\\n|,|"/', $field)) { $field = '"' . str_replace('"', '""', $field) . '"'; } echo $separator . $field; $separator = ','; } echo "\r\n"; } } } Edited by raymak, 25 May 2014 - 02:04 PM. Hi people. Need some help if anyone could give a hand! I'm currently trying to incorporate an export to Excel feature on search returns on my web page. Here is how my searches are returned, so what I want now is when the user clicks on the 'Export to Excel' button it downloads the search results and opens it in the same format in Excel. I've tried using http://phpexcel.codeplex.com/ but can't understand how to use it properly, does anyone have any suggestions? I don't have any code written for the Export to Excel yet as it's just a submit button. How I see it in my head is the user clicks the button, it goes to a new page and performs a new query then downloads that but I don't no if thats right or not. How can I use PHP to export my database into a .sql file? hello guys.. i want help from u . i am displaying a table of 5 rows and 5 columns . i want to get a pdf copy of it dynamically. i want to re-use it again for my invoice also . covert in into pdf and then print that file. can u provide a sample code of how to covert it into pdf . (same as exporting into excel) Hi all, this is the code i'm using at the moment which is at the bottom of a webpage Code: [Select] // Open file export.csv. $f = fopen("export.csv", "w"); // Put all values from $out to export.csv. fputs($f, $out); fclose($f); $filename = "StatisticalAnalysis-" . gmdate("Y-m-d-H-i-s") . ".csv"; header("Content-type: application/csv"); header("Content-Disposition: attachment; filename=" . $filename); readfile("export.csv"); The variable named $out is a long line of text in csv format. I've echoed that variable and it's all good. When a checkbox in a form further up the page is checked the code creates and fills in the $out variable and then carries out the code above. The problem i have is that when the csv save dialog comes up and the file is saved, all it contains is a copy of the html code which is on that page, not the info stored in the $out variable. Can anyone offer any advice on what the problem is? Cheers hello I wrote a php code which will get the records from database and save them in excel. <?php $t = strtotime($date1); $t1 = strtotime($date2); $t2 = $t1 - $t; $t3 = floor($t2 /60/60/24); $j = 0; while ($j <= $t3 ) { if ($j == 0) { $t = $t - 86400; } $t = $t + 86400; $today = date('Y-m-d',$t); mysql_select_db("reporting", $connect); $result1 = mysql_query("SELECT * from report where date = '$today' "); $row1 = mysql_fetch_assoc($result1); ?><tr><?php foreach($row1 as $k=>$v){ ?> <td><?php echo $v; $op1 = $row[$v]; ?></td> <?php } ?></tr><?php $j++; } ?> </table> <body> </html> <?php mysql_close($connect); header("Content-type: application/vnd.ms-excel"); header('Content-disposition: attachment; filename = "report" '); exit; ?> Problem is I am able to retrieve only 2 rows to excel file. If the number of rows are more than 2 it displays a table. can any one help me Hi everyone, I got a bit of code off the web and did some tweaking. I want to use it to export data from a mysql table to excel. I do a website for a friend and have been exporting it myself and emailing it to him. However, I thought it'd be easier if I could just direct him to a link so he could get it whenever. Anyway, the code below works pretty well...the only problem being that it exports all data to the first column of the excel file. There are commas between all fields, so it is possible to use the 'text to columns' feature in excel to separate teh data into separate columns. However, if there is a way of fixing the code that would negate the need to have to do this, it would be much appreciated. Here goes: <?php $db = mysql_connect("localhost", "MYUSERNAME", "MYPASSWORD"); mysql_select_db("MYDATABASE",$db); $query="SELECT * FROM MYTABLENAME"; $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); $csv_output = "firstname,lastname,emailaddress,crew_name_001"; $csv_output .= "\r\n"; $i=0; while ($i < $num) { $id=mysql_result($result,$i,"id"); $firstname = mysql_result($result,$i,"firstname"); $lastname = mysql_result($result,$i,"lastname"); $emailaddress = mysql_result($result,$i,"emailaddress"); $crew_name_001 = mysql_result($result,$i,"crew_name_001"); $csv_output .= "$firstname,$lastname,$emailaddress,$crew_name_001\n"; ++$i; } $mode="xls"; $type="excel"; header("Content-type: text/x-csv"); header("Content-disposition: attachment; filename=".date("d-m-Y")."-export.xls"); print $csv_output; exit; ?> Thanks for your time, Dave Hi, this is my first time here. i am trying to create an xls file from the data i get from mysql. here is the code i tried but i am not able to use it correctly. Code: [Select] ob_start(); include('config'); $datacat = mysql_query("SELECT * FROM `leads`") or die(mysql_error()); $name = mysql_fetch_assoc($datacat); $line1="Industry,Company Name,Officials Name,Job Title,Country,Direct Number Mobile Number,Switch Board Number,E-mail,Executive NamePitch Date,Call Back Date,Comments\t"; while($row = mysql_fetch_array($datacat, MYSQL_ASSOC)) { $line2= $name['industry'].",".$name['company_name'].",".$name['officials_name'].",".$name['job_title'].",".$name['country'].",".$name['direct_number_mobile_number'].",".$name['switch_board_number'].",".$name['email'].",".$name['executive_name'].",".$name['pitch_date'].",".$name['call_back_date'].",".$name['comment']."\t"."\n"; } $data="$line1\n$line2\n"; header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=extraction.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; i get my webpage title in the top of xls file and all the fields in xls file are separated by commas, whereas i want them to be in proper tables. Help would be much appreciated. I have a script that will export data to excel. After the export, I need the page to reload showing status information, but it does not reload. What could be causing an issue like this? I think that because the export forced the download file dialogue to open, those headers may be preventing the form from reloading properly, but how, why, and what can be done to resolve the issue? Hey guys! I have the following script to create an excel file, the thing is that I dont want to be asked if I want to open or save the file when accessing the php file...I just want the php file directly to save the excel file. Heres the code: $filename = "test.xls"; $contents = "testdata1 \ntestdata2 \ntestdata3 \n"; header('Content-type: application/vnd.ms-excel'); header('Content-Disposition: attachment; filename='.$filename); echo $contents; Is there a way instead of using the header function, use something like: fopen, fwrite, fclose ? Thanks in advance! Cheers, I am trying to export multiple csv files to download from 2 separate tables in my database. Some background: I have a web app that links to a phpmyadmin database. There are 2 tables in the database (entering and exiting). These tables hold the phone inventory information of employees currently entering or exiting the organization. The fields in my tables a location, firstname, lastname, username, extension, mac, type What I am trying to do is export the data in these 2 tables to CSV (which I have working now) but I need to have multiple CSVs for each. For example, for my exiting table, I need to have one CSV export all the fields in the table and I also need another CSV to export just the location and username field. I have a simple html form with a submit button which is currently working now: <form action="exportexiting.php" method="POST" style="width: 456px; height: 157px"> <div> <fieldset> <legend style="width: 102px; height: 25px"><strong>Entering CSV:</strong></legend> <input name="Export" type="submit" id="Export" value="Export"> </fieldset><br/> </div> </form> This links to my exportexiting.php file: <?php $host = 'localhost'; $user = 'root'; $pass = 'xxxx'; $db = 'PhoneInventory'; $table = 'exiting'; // Connect to the database $link = mysql_connect($host, $user, $pass); mysql_select_db($db); require 'exportcsv.inc.php'; exportMysqlToCsv($table); ?> Then to exportcsv.inc.php: <?php function exportMysqlToCsv($table,$filename = 'export.csv') { $csv_terminated = "\n"; $csv_separator = ","; $csv_enclosed = ''; $csv_escaped = "\\"; $sql_query = "select * from $table"; // Gets the data from the database $result = mysql_query($sql_query); $fields_cnt = mysql_num_fields($result); $schema_insert = ''; for ($i = 0; $i < $fields_cnt; $i++) { $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed; $schema_insert .= $l; $schema_insert .= $csv_separator; } // end for $out = trim(substr($schema_insert, 0, -1)); $out .= $csv_terminated; // Format the data while ($row = mysql_fetch_array($result)) { $schema_insert = ''; for ($j = 0; $j < $fields_cnt; $j++) { if ($row[$j] == '0' || $row[$j] != '') { if ($csv_enclosed == '') { $schema_insert .= $row[$j]; } else { $schema_insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed; } } else { $schema_insert .= ''; } if ($j < $fields_cnt - 1) { $schema_insert .= $csv_separator; } } // end for $out .= $schema_insert; $out .= $csv_terminated; } // end while header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Length: " . strlen($out)); // Output to browser with appropriate mime type, you choose header("Content-type: text/x-csv"); //header("Content-type: text/csv"); //header("Content-type: application/csv"); header("Content-Disposition: attachment; filename=$filename"); echo $out; exit; } ?> Again, this is working perfectly for only exporting all the data from the exiting table into one CSV file. My question is, how can I make my one submit button export the 2 CSV files that I need? Thanks for the help... |