简体   繁体   English

导出到CSV与表PHP不同

[英]Export to CSV not same as table PHP

I am trying to download table data into a CSV format. 我正在尝试将表格数据下载为CSV格式。 The data in one of the fields contains ",". 字段之一中的数据包含“,”。 Eg: Doe, John 例如:Doe,John

When I download the csv file, the data after comma is shifted to next column. 当我下载csv文件时,逗号后的数据将移至下一列。 But I want the entire data ie including comma in same column. 但是我想要整个数据,即在同一列中包含逗号。

The Code I used as follows: 我使用的代码如下:

<?php
include('dbconfig.php');
//header to give the order to the browser
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=download.csv');
//select table to export the data
$sql ="SELECT * FROM tablename";
$select_table=mysqli_query($db, $sql);
$rows = mysqli_fetch_assoc($select_table);

if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
 getcsv($rows);
 $rows = mysqli_fetch_assoc($select_table);
 }

  // get total number of fields present in the database
 function getcsv($no_of_field_names)
 {
   $separate = '';


  // do the action for all field names as field name
  foreach ($no_of_field_names as $field_name)
 {
 if (preg_match('/\\r|\\n|,|"/', $field_name))
 {
  $field_name = '' . str_replace('<em>', '', $field_name) . '';
  }
  echo $separate . $field_name;

 //sepearte with the comma
 $separate = ',';
  }

//make new row and line
echo "\r\n";
}
?>

Can someone help me get through this issue. 有人可以帮我解决这个问题。 Thanks 谢谢

Make sure you escape the , . 确保你逃脱, Typically values that contain sensitive characters (such as , and \\n ) are surrounded in " . 通常包含敏感字符(如值,\\n )被包围在"

So your output can be: 因此,您的输出可以是:

 "Doe, John",52,New York

You can either write your own escape function or use PHPs fputcsv . 您可以编写自己的转义函数或使用PHP fputcsv It writes to a file handler that's a bit inconvenient but you can make it stdout . 它写入文件处理程序有点不方便,但是您可以将其设置为stdout

$handle = fopen("php://stdout");
fputcsv($handle, array("Doe, John", 52, "New York"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM