On my local machine it is working fine. but on server it is printing the output on the same page instead of creating of a CSV file. can anyone help
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=memberList.csv');
ob_end_clean();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('First Name', 'Last Nameenter code here', 'Street Name', 'City', 'State', 'Zip Code'));
// fetch the data
$csvQry = "SELECT * from tabel where num=1";
if ($_POST['stateList']!='all'){
$csvQry = "SELECT * from table";
}
$csvRows = mysqli_query($db,$csvQry);
// loop over the rows, outputting them
while ($csvRow = mysqli_fetch_assoc($csvRows)) {
fputcsv($output, $csvRow);
}
fclose($output);
Related
I am trying to create a csv with PHP, that separate the the headers and columns.
Currently I am able to create the csv and dump the data, but each row in dumped into one cell.
The result is:
I expected this:
Here is my code
<?php
// Load the database configuration file
require_once('db/connect_db.php');
//$time = date('Y-m-d:').preg_replace("/^.*\./i","", microtime(true));
$time = date('Y-m-d');
$dteTimetamp = date('Y-m-d');
// Fetch records from database
$find = $conn->prepare("SELECT School, SchoolAddress, School_Email, Principle_Name, Reception_Number, QuantityFingerPrintScanner, InvoiceNumber from School");
$find->execute();
$udonr = "$dteTimetamp" . "Request";
//$filename = "$udonr.csv";
// Create a file pointer
$f = fopen(dirname(__FILE__).'/testfolder/'.$udonr.'.csv', 'w');
// Set column headers
$header = array('School Name', 'Contact Person', 'Contact Number', 'School Address', 'Number of scanners to deliver', 'Invoice Nuber');
fputcsv($f, $header);
// Output each row of the data, format line as csv and write to file pointer
while($row = $find->fetch(PDO::FETCH_ASSOC)){
$lineData = array($row['School'], $row['Principle_Name'], $row['Reception_Number'], $row['SchoolAddress'], $row['QuantityFingerPrintScanner'], $row['InvoiceNumber']);
fputcsv($f, $lineData);
// Set headers to download file rather than displayed
//header('Content-Type: text/csv');
// header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
//exit;
#FROSIT is right. Excel is kinda dumb about opening CSV files, especially ones with comma separator (ironically).
Your file looks good but if you need to have it automatically open in Excel (e.i. someone else will need to open it), you might want to find which one is the default separator for Excel and set that in your script.
trying to export my table to CSV file but I seem to be lost on what am doing wrong,
I have my loaddata.php that has table that shows fields
I have my Connection.php that will have database connection
but when I run result what am getting is it exporting CSV with columns, but data is is bring back loaddata.php page with HTML formatting and every result
I have tried moving the included "loaddata.php" than I get brought back blank excel page with columns
<?php include('connection.php');
if(isset($_POST["export"])){
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=loaddata.csv');
$output = fopen("php://output", "w");
fputcsv($output, array(
'row number',
'Position ID',
'Description',
'firstname',
'lastname',
'country ',
'PhoneNumber'));
include ("loaddata.php")
$sqlcsv = "SELECT * FROM employeeTable";
$resultcsv = mysqli_query($conn,$sqlcsv)
or die('Invalid query sqlcsv: ' . mysqli_error());
while ($row = mysqli_fetch_assoc($resultcsv))
{
fputcsv($output, $row);
}
fclose($output);
}
?>
How to export grabbed data to .csv file? I'm using php simple html dom to parse data. Here is the code:
foreach ($linkoviStranica as $stranica)
{
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
echo "<strong>".$name[0]->innertext."<strong>"."<br>";
if (!empty($onlinePrice[0]->innertext))
{
echo $onlinePrice[0]->innertext."<br>";
}
if (!empty($diffPrice[0]->innertext))
{
echo $diffPrice[0]->innertext."<br>";
echo "---------------------"."<br>";
}
}
I want to export, $name, $onlinePrice, $diffPrice to csv file with header in the following format:
name onlinePrice diffPrice
example 10 44
xxxx 412 461
zzzzz 1414 41
Could you please help me? Thanks!
Something like this:
// Define a array to hold all the data
$data = [];
// OR use this line if you want the headers with names on the first line of the file
// $data = [['name', 'onlinePrice', 'diffPrice']];
// Loop the raw data
foreach ($linkoviStranica as $stranica) {
$podaciStranice = "http://someurl/$stranica";
$data = file_get_html($podaciStranice);
$name = $data->find('div[class="price-card-name-header-name"]');
$onlinePrice = $data->find('div[class="price-box online"]');
$diffPrice = $data->find('div[class="price-box paper"]');
// Add current row to out array
$data[] = [
$name[0]->innertext,
$onlinePrice[0]->innertext,
$diffPrice[0]->innertext
];
}
// Open a new file. Replace the file name with the name you'd like
$fp = fopen('file.csv', 'w');
// Loop each row in the data array
foreach ($data as $fields) {
// This method converts a row to a CSV line (http://php.net/manual/en/function.fputcsv.php)
fputcsv($fp, $fields);
}
// Close the file handler
fclose($fp);
$header ="SNo , Order Date , Order Number , Compaign , Amount , Order Status , Used Date , Cancel Reason , Order Commision , Payment Date , Payment Status \n";
$header1 =$header ;
$result='';
foreach ($data as $fields) {
$result= 'echo your data with coma seprated '."\n";
}
$all=$header.$result;
$name="report.csv";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=".$name);
header("Pragma: no-cache");
header("Expires: 0");
print "$header1 $result";
I'm having a problem writing the results of a MySQL query to a file using php. There are definitely results from the search, and the file is created, but when you open the file it's empty. I think it's something to do with how I'm writing to the file, but I'm not sure.
$result = mysql_query($compsel);
if(!result) die("unable to process query: " . mysql_error());
$fp = fopen('results.csv','w');
mysql_data_seek($result,0); //set data pointer to 0
$rw = mysql_fetch_array($result, MYSQL_ASSOC);
print_r($rw);
foreach ($rw as $fields){
fputcsv($fp, $fields);
}
fclose($fp);
Thanks in advance!
Here's an example:
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
You can modify it to suit your needs.
Source: http://code.stephenmorley.org/php/creating-downloadable-csv-files/
I am using below code to export CSV file using fputcsv in PHP. Code works proper and CSV file generates. All the values/records are coming from database. But I want to add dollar ($) symbol with some of column values.
Code for exporting CSV file.
$filename1 = "All Months.csv";
ob_end_clean();
$fp1 = fopen('php://output', 'w');
ob_start();
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename='.$filename1);
fputcsv($fp1, array('Month', 'Year', 'Total Production', 'Credit Adjustments', 'Net Production', 'Hygiene Production', 'Collections', 'Account Receivable Total', 'New Patients', 'Break Even Points', 'Net Income', 'Hygiene %'));
$query = $db->query("SELECT Month, Year, Total_Production, Credit_Adjustments, Net_Production, Hygiene_Production, Collections, AC_Receivable_Total, New_Patients, Break_Even_Points, Net_Income, Hygiene FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}
exit();
Snapshot of exporting file -
If you want just to add $ sign you can do it this way:
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$row['the_field_you_want'] = '$'.$row['the_field_you_want']
fputcsv($fp1, $row);
}
While using select query itself you can concat $ symbol. Like below
$query = $db->query("SELECT concat('$',Net_Income) as Net_Income FROM clientsdata WHERE Client_Id = '".$userID."'");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp1, $row);
}