Reputation: 1820
This is kind of silly and unecessary but also kind of a waste of time since I am doing this every day. But I am wondering if there is a way to export data using PHP to CSV that does not require the use of the text import wizard when opening the file in excel.
Currently my code looks like this which I think seems to be pretty standard every where I look:
header("Content-type: text/csv");
header('Content-Disposition: attachment; filename=exported_shipments_'.date("Ymd").'.csv');
header("Pragma: no-cache");
header("Expires: 0");
echo "name" . "\t";
echo "address_1" . "\t";
echo "address_2" . "\t";
echo "city" . "\t";
echo "province_code" . "\t";
echo "postal_code" . "\t";
echo "country_code" . "\t";
echo "phone" . "\t";
echo "package_contents" . "\t";
echo "description" . "\t";
echo "value" . "\t";
echo "value_currency" . "\t";
echo "order_store" . "\t";
echo "order_id" . "\t";
echo "package_type" . "\t";
echo "size_x" . "\t";
echo "size_y" . "\t";
echo "size_z" . "\t";
echo "size_unit" . "\t";
echo "weight" . "\t";
echo "weight_unit" . "\t";
echo "postage_type" . "\t";
echo "signature_requested" . "\t";
echo "insurance_requested" . "\t";
echo "ship_date" . "\t";
echo "\n";
And so on.
Is there anything I can do so that excel recognizes that I want it to be delimited right away instead of having to use the wizard?
Upvotes: 0
Views: 1546
Reputation: 461
You're using tab, not comma to separate the CSV. You also can force the Content-Type to application/vnd.ms-excel, and set the extension to .xls, it'll open with Excel and automatically import CSV.
You can use this code to do this:
<?php
header ( "Content-type: application/vnd.ms-excel");
header ( "Content-Disposition: attachment; filename=exported_shipments_" . date ( "Ymd") . ".xls");
header ( "Pragma: no-cache");
header ( "Expires: 0");
$data = array ();
$data[] = "name";
$data[] = "address_1";
$data[] = "address_2";
$data[] = "city";
$data[] = "province_code";
$data[] = "postal_code";
$data[] = "country_code";
$data[] = "phone";
$data[] = "package_contents";
$data[] = "description";
$data[] = "value";
$data[] = "value_currency";
$data[] = "order_store";
$data[] = "order_id";
$data[] = "package_type";
$data[] = "size_x";
$data[] = "size_y";
$data[] = "size_z";
$data[] = "size_unit";
$data[] = "weight";
$data[] = "weight_unit";
$data[] = "postage_type";
$data[] = "signature_requested";
$data[] = "insurance_requested";
$data[] = "ship_date";
$fp = fopen ( "php://output", "w");
fputcsv ( $fp, array_values ( $data), ",", "\"");
fclose ( $fp);
?>
Upvotes: 2