PHP - Problem Exporting Data To Csv File
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 Similar TutorialsHi, 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. Hello,
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. How can I use PHP to export my database into a .sql file? 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? 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 So here is my code: //form.html <form action="http://localhost/lab3/index.php" method="post " > <input type="text" name="numar" value=""><br> <input type="submit" name="submitButton" value="Submit"> </form> //and in index.php ,which is in the specified folder if I write : if($_POST['numar']!="") $m=$_POST['numar']; //then I get an error saying Undefined index: numar I really read a lot about forms and saw examples , but I can't figure out what's wrong. If you have any ideas.. 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. 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(); } } 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 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 Well, im a n00b for php, and what i need is a php script which will read data from .xml file and write it into .txt file. Can someone help me? Example of .xml file : <?xml version="1.0" encoding="utf-8"?> <tv generator-info-name="NeTXMLTV/1.0.0.0" source-info-url="http://www.net-tv.hr/" source-info-name="NeT TV XMLTV" source-data-url="http://www.net-tv.hr/xmltv/net-pregled-programa-xmltv.xml"> <programme channel="NeT TV" start="20110413063000 +0200" stop="20110413080000 +0200"> <title lang="hr">JUTARNJI EXPRESS</title> <category lang="hr">glazbeno-informativni program</category> <desc lang="hr">Glazbeno informativna emisija sa servisnim informacijama i jutarnjim temperaturama, idealna za jutarnje buđenje uz toplu kavu ili čaj....</desc> </programme> </tv> I need the .txt file to look like this: 201104130630 - 201104130800 JUTARNJI EXPRESS glazbeno-informativni program Glazbeno informativna emisija sa servisnim informacijama i jutarnjim temperaturama, idealna za jutarnje buđenje uz toplu kavu ili čaj.... Can someone please help me? thanks hello, (firts of all, I'm not a php-expert, I just understand the code a little, but I can't write it myself..) I'm using the attached php file (which I found online) to get data out of the attached xml file.(had to rename it to .doc to get it uploaded) What I actually want is the following: From every "User" element showing the attribute "LoginName", and then show under every "LoginName" all the (element)"Contact" and (attributes) "Name" and "Email", right now I just can get the Name, or Email.. example what I would like to have: (using the attached iebo.xml) LoginName: Dirk Contact Name="dirk" Email="dirk@dirk.nl" Contact Name="dirk2" Email="dirk2@dirk.nl" LoginName: test1 Contact Name="test" Email="test@test.nl" Contact Name="test2" Email="test2@test.nl" Thanks for any help in advance Dirk Hi, I need some help, im trying to extract data from a file and display results as text. Example. File: TitanicRomance1990.jpg Output: Movie Name: Titanic Year : 1990
Thank you in Advanced. 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, Hi, I'm quite new to PHP and I'd like to know if there's a way for me to use some PHP solution to get data from another PHP file instead of used AJAX. My intention is to have some kind of a loop in one PHP file that'll have a variable that gets the returned data from a different PHP file on every iteration and does something with it. Would be simple enough to do it with Ajax but I can't use it in this instance. Any thoughts? is there a php solution that will take the raw data from one file and paste it into another text file? I have a master file and a download file that always starts at quarter past midnight . this data needs to be pasted into the master file, in the correct place , possibly overlapping and replacing data that already exists. the length of the download file will vary but will always start at 00. 15 the two files are www.maidenerleghweather.com/download.txt and also www.maidenerleghweather.com/master.txt any help appreciated . hello, I need xml file as playlist.xml and i want to retrive data from my mysql table. I have the following code as i am trying to use php code inside playlist.xml file. Code: [Select] <?xml version="1.0" encoding="utf-8"?> <xml> <?php $dbhost='localhost'; $dbuser='pavel'; $dbpass='pavel123'; mysql_connect($dbhost,$dbuser,$dbpass); mysql_select_db("amarmusic"); $sql=("select *from bband where artist='Meghdol' and album='Drohe Montre Valobasha';"); $res = mysql_query($sql); while ($result = mysql_fetch_array($res)){ ?> <track> <path> <? $result['link']?></path> <title><? $result['title']?></title> </track> <? } ?> </xml> but unfortunately its not working. any1 have any idea how to fix it? please help me. Hello, How can I get the id in the search bar into the viewuser.php file ... <?php foreach($myObjectMap as $key => $item): ?> <tr> <td> <a href="viewuser.php?id=<?PHP echo $item->ID; ?>"> <?PHP echo $item->UserName; ?> </td> ...
Hi, I am updating a few parts of my current website. Currently, the website updates user accounts by uploading CSV data reports. I currently use fgetcsv to deal with each row and this is taking forever to deal with the data as this is currently the code for each row. while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $grabinfo = "SELECT * FROM transactions WHERE id = '$data[$i]'"; $grabinforesult = mysql_query($grabinfo) or die(mysql_error()); while($row = mysql_fetch_array($grabinforesult)){ $merchant = $row['merchant']; $username = $row['username']; $datetime = $row['datetime']; $letthem = $row['letthem']; $validate = "SELECT * FROM transactions WHERE merchant = '$merchant' and username = '$username' and (status='pending' or status='success' or status='confirmed') and datetime='$datetime'"; $validator = mysql_query($validate) or die(mysql_error()); if(mysql_num_rows($validator) >= $letthem) { $import="UPDATE transactions SET amount='0.00' WHERE id='$data[$i]' and status ='awaiting'"; mysql_query($import) or die(mysql_error()); }} mysql_query($import) or die(mysql_error()); } fclose($handle); This is performing lots of checks on the csv data and checking it with the system. It checks each row. Is there a quicker way of reading the csv data? There are lots of checks and while loops within the fgetcsv while loop. It can take upto half an hour to process a file with 1000 csv rows. Hope someone could offer some advise. Thanks Hi, I am not that versed in PHP. I have been working with this snippet of code that I found on a tutorial site. It works like 97% and I get the format mostly like I need it. Except, I can not figure how to add an extra single node to the list. The code generates 20 random numbers and puts them into an array. The array is then used to create a numbers node in the xml file. It goes through and creates all the nodes. I can not seem to figure out how to put a single game numbernode at the top of all the numbers nodes. I am also not understanding how to write the output to create the actual xml file. I have written code in the past to write a string to a text file but I am not sure about this because it is in an array? The xml file will be appended every 5 minutes for data comparison down the road. I think I will need to add a routine that calls the data back in at the beginning of the script and looks for the last game number if it is there and add 1. The game number must increment each time it is appended. Any ideas on how to finish this up? The final out put will look like this. I only did a few lines instead of all 20 numbers to keep this short. Code: [Select] <?xml version="1.0"> <Container> <gamenumber>10</gamenumber> <numbers>47</numbers> <numbers>10</numbers> <numbers>5</numbers> <numbers>27</numbers> </Container> My Script Code: [Select] <?php $balls = range(1,80); shuffle($balls); $pick = array_slice($balls,1,20); //$drawn = implode(", ",$pick); $arraySize = sizeof($pick); // print ("Arraw is $drawn\n\n"); $doc = new DOMDocument(); $doc->formatOutput = true; $drawn = array(); $r = $doc->createElement( "Container" ); $doc->appendChild( $r ); for ($i=0; $i!= $arraySize; $i++){ $drawn [] = array( 'numbers' => $pick[$i], ); } foreach( $drawn as $draw ) { $numbers = $doc->createElement( "numbers" ); $numbers->appendChild( $doc->createTextNode( $draw['numbers'] ) ); $r->appendChild( $numbers); } echo $doc->saveXML(); ?> Thanks for your advise and help!!! |