What I have done is get the data from MySQL to excel in csv format but I am not getting the entities of that table like if I have a table member having these 3 entities
memberid membername memberemail
I am getting the data of these entities like
1 alishah test#test.com
What I want is when I download an excel it gets header with it like
memberid membername memberemail
1 alishah test#test.com
What I did for excel is
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp= fopen('php://output', 'w');
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
Simply write a line with the column headers before writing the data to the csv.
<?php
$selectUserData = "SELECT * FROM tbl_member";
$export = $conn->query($selectUserData);
$fp = fopen('php://output', 'w');
fwrite($fp,'"memberid","membername","memberemail"'."\n");
foreach ($export as $fields)
{
fputcsv($fp, $fields);
}
header("Content-Type: text/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename=member.csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
Related
I have the following code:
PhP
function write_csv($filename, $rows) {
$file = fopen($filename, 'w');
while($row = mysqli_fetch_assoc($rows)) :
fputcsv($file, $row);
endwhile;
fclose($file);
}
// $db is a class I have and this function just returns a SQL result set
$result_set = $db->run_query("SELECT * FROM Users");
write_csv('../MOCK_USERS_DATA.csv', $result_set);
I am correctly getting a created CSV file with the the users information for example
1,greg,mason,407-356-3322,greg#gmail.com
2,derek,herd,407-234-4352,derek#gmail.com
etc...
My question is how do I get the headers from the table as the first row in my CSV file. I am new to creating CSV files and am stuck on getting that first row of headers in that file that match the name of the column in my database. Any suggestions?
Easy export to CSV
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
ob_start();
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings -> trim is used for lang translates
// or use SQL query to get table columns headers name
fputcsv($output, array(
trim('Product name'),
trim('Pellet number'),
trim('Quantity'),
trim('Date')
), ";");
// use foreach
***********
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header('Content-Disposition: attachment; filename=pelletlist-' . time() . '.csv');
header("Content-Transfer-Encoding: binary");
header("Cache-control: private"); //use this to open files directly
header('Expires: 0');
header("Pragma: no-cache");
header("Connection: close");
fclose($output);
exit();
for load column name from db use:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
or
SHOW COLUMNS FROM my_table;
I've been trying to export MySQL fields to CSV and can get all them exporting correctly except the filed which contains HTML.
My MySQL table is made up as follows:
Name: Address: Profile:
Name is simply text as with address, but profile is HTML
My array is:
$array = array ( array ( "Name" => "$name", "Address" => "$address", "Profile" => $profile )
);
Made using:
$name = $info['name'];
$address = $info['address'];
$profile = $info['profile'];
I have a "Tab" \t delimiter and every exports into the CSV correctly bar the HTML which I would like to keep as pure HTML but in one Excel field, at the moment is splits across multi rows and fields.
CSV code is as follows:
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$titleArray = array_keys($array[0]);
$delimiter = "\t";
$filename="profiles.xls";
foreach ($array as $subArrayKey => $subArray) {
$dataRowString = implode($delimiter, $subArray);
print $dataRowString . "\r\n";
}
Any help or advise would be highly welcomed.
You need to escape the field values. You can use fputcsv:
$stdout = fopen('php://stdout', 'w');
fputcsv($stdout, $subArray, "\t");
$filename="profiles.xls";
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
$titleArray = array_keys($array[0]);
$delimiter = "\t";
$stdout = fopen('php://stdout', 'w');
foreach ($array as $subArrayKey => $subArray) {
fputcsv($stdout, $subArray, $delimiter);
}
I am trying to export mysql data into csv file,but the problem is that the csv file shows the name of fields not the fields data in csv file.
Here is my php code
<?php
error_reporting(0);
include"../connection.php";
$output = fopen('php://output', 'w');
$query = "SELECT 'claim_dateclaim','claim_clientname', 'claim_account', 'claim_contract', 'claim_parcelno', 'claim_refno', 'claim_datecollected', 'claim_coladdress', 'claim_colpostcode', 'claim_counsineaddres', 'claim_conpostcode', 'claim_retailvalue', 'claim_claimvalue', 'claim_protitle', 'claim_reason', 'claim_type', 'claim_repparcelno' FROM tbl_claimdetail ";
$rows = mysql_query($query );
fputcsv($output, array('Claim Date Raised','Client Name','Account no','Contract Number','Parcel Number','Company','Claim Ref no','Collection Date', 'Collection Address','Collection Postal code','Consignee Address','Consignee Post Code','Retail value','Claim value','Product','Reason','Type','Replacement no'));
while ($row = mysql_fetch_assoc($rows)) {
fputcsv($output, $row);
}
fclose($output);
header("Content-type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=discussdesk".date('dmY').".csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
And here is my csv file
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/9GNh6.jpg
use:
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
fputcsv($fp, array_values($row));
}
associative array will work with array_values
I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.
So I am taking that main source file then reading and putting the data in a "PROPER" csv file.
The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".
My code
$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
foreach ($data as $item) {
// echo $item;
fputcsv($fh, array($item));
}
}
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
Any help is highly appreciated. Thanks in advance.
Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:
header("Content-Disposition: attachment; filename=\"$filename.csv\" );
i have a table which shows some mysql data, every entry has a checkbox to select individual entries, now i want to be able to export those selected entries into a xml or txt file, i tried this:
<?php
if ($_POST['exporttxt']) {
for ($i = 0; $i < count($_POST['checkbox']); $i++) {
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);
}
$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n";
if ($result->num_rows > 0) {
while ($myrow = $result->fetch_assoc())
{
$output .= "\t<row>\n";
foreach ($myrow as $_name => $_value)
{
$output .= "\t\t<$_name>$_value</$_name>\n";
}
$output .= "\t</row>\n";
}
}
$output .= "</root>";
}
header('content-type: text/xml');
header('content-disposition: attachment; filename=data_export.xml');
echo $output;
exit;
?>
But that didn't work at all, any hints ?
I've changed the code a bit, i am now using this
<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM ticket WHERE id='$export_id'");
$text = mysql_fetch_assoc($text);
$text = $text["code"];
ob_end_flush();
header("Content-type: text/plain");
header("Content-disposition: attachment;filename=\"filename.txt\"");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo($text);
}
}
?>
I now get proper output on my screen, but it won't offer me to download the file ?
Your original code was querying each of the checkboxed IDs individually (a long and laborious way to handle it) and was trying to dump the results individually per row (not going to work well for you).
Try this. (NOTE: Untested, but should give you a good starting point to develop.)
if( $_POST['exporttxt'] ){
if( count( $_POST['checkbox'] )>0 ){
// If the checkbox values are meant to all be integers, you might want to perform some validation/sanitisation/filtering here
// Up to you to do that
// Collapse the IDs from the checkboxes into a comma-delimited string
$export_ids = implode( ',' , $_POST['checkbox'] );
// Template the SQL Query
$sqlTpl = 'SELECT code FROM ticket WHERE id IN ( %s )';
// Compile the SQL Query String
$sqlStr = sprintf( $sqlTpl , $export_ids );
// Execute the SQL Query
if( !( $sqlRes = mysql_query( $sqlStr ) ) ){
// SQL Error - Log it, Handle it
}elseif( mysql_num_rows( $sqlRes )==0) {
// No Rows Returned - Log it, Handle it
}else{
// We have results - process them
$text = array();
while( $r = mysql_fetch_assoc( $sqlRes ) ){
// Looping through the returned rows, adding them to the $text array
$text[] = $r['code'];
}
// Collapse the $text array down into a normal string, with one element per line
$output = implode( "\n" , $text );
// Output Handling from #narcisradu's answer
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"filename.txt\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo $output;
die; // Prevent any further output
}
}else{
// No Checkboxes Checked
echo 'You must select one or more checkboxes to export something, muppet.';
}
}
First of all:
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);}
This piece of code will actually do a query for every element in _POST['checkbox'] array but then you are using the result of the last query and you are not parsing the result of every query.
Please make sure the generated XML is well-formed and you actually have some data, by displaying directly into the browser.
After that you may try to force download:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"".urlencode(basename($file_name))."\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
ob_end_flush();