在使用php中的换行符生成csv时出现小故障

我只是根据存储在mysql表中的数据生成一个csv文件。 生成的csv,当在excel中打开时,似乎大多是好的,但是每当它有一个换行符时,excel就会将数据放在一个新行上。 任何想法如何防止呢?

样本数据

line 1 some data another data 

CSV生成代码:

 header("Content-Type: text/csv; charset=UTF-8"); header("Content-Disposition: attachment; filename=\"".$MyFileName."\""); $filename = $MyFileName; $handle = fopen("temp_files/".$filename, "r"); $contents = fread($handle, filesize("temp_files/".$filename)); fclose($handle); echo $contents; exit; 

内容片段我用来摆脱新行(没有工作):

 $pack_inst = str_replace(',',' ',$get_data->fields['pack_instruction']); $pack_inst = str_replace('\n',' ',$pack_inst); $pack_inst = str_replace('\r',' ',$pack_inst); $pack_inst = str_replace('\r\n',' ',$pack_inst); $pack_inst = str_replace('<br>',' ',$pack_inst); $pack_inst = str_replace('<br/>',' ',$pack_inst); $pack_inst = str_replace(PHP_EOL, '', $pack_inst); $pattern = '(?:[ \t\n\r\x0B\x00\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}]|&nbsp;|<br\s*\/?>)+'; $pack_inst = preg_replace('/^' . $pattern . '|' . $pattern . '$/u', ' ', $pack_inst); $content .=','.$pack_inst; 

根据RFC 4180 ,如果列的内容包含行分隔符( \r\n ),列分隔符( , )或string分隔符( " ),则必须将内容括在双引号内" 。 当你这样做的时候,你必须通过在其他内容之前转义所有的"字符" 。 所以下面的CSV内容:

 1: OK,2: this "might" work but not recommended,"3: new line","4: comma, and text","5: new line and ""double"" double quotes" 1: Line 2 

将产生2行CSV数据,第一行包含5列。

话虽如此,看看fputcsv()函数。 它会为你处理大部分血淋淋的细节。

你显示的不是CSV代码,它只是你用来强制下载到浏览器的代码。 无论如何,你需要sorting的函数是fputcsv() ,它会自动考虑各种边界情况,你写任何代码将表格数据转换为CSV格式可能不会考虑。

你说你正在把这个基于MySQL表中的数据,这里是一个创buildCSV文件的基本框架,假设以程序方式使用MySQLi扩展:

 <?php // Connect to database and generate file name here $fileName = 'file.csv'; // Get the data from the database $query = " SELECT * FROM table_name WHERE some_column = 'Some Value' ORDER BY column_name "; if (!$result = mysqli_query($db, $query)) { // The query failed // You may want to handle this with a more meaningful error message header('HTTP/1.1 500 Internal Server Error'); exit; } else if (!mysqli_num_rows($result)) { // The query returned no results // You may want to handle this with a more meaningful error message header('HTTP/1.1 404 Not Found'); exit; } // Create a temporary file pointer for storing the CSV file $tmpFP = fopen('php://temp', 'w+'); // We'll keep track of how much data we write to the file $fileLength = 0; // Create a column head row and write first row to file $firstRow = mysqli_fetch_assoc($result); $fileLength += fputcsv($tmpFP, array_keys($firstRow)); $fileLength += fputcsv($tmpFP, array_values($firstRow)); // Write the rest of the rows to the file while ($row = mysqli_fetch_row($result)) { $fileLength += fputcsv($tmpFP, $row); } // Send the download headers header('Content-Type: text/csv; charset=UTF-8'); header('Content-Disposition: attachment; filename="'.$fileName.'"'); header('Content-Length: '.$fileLength); // Free some unnecessary memory we are using // The data might take a while to transfer to the client mysqli_free_result($result); unset($query, $result, $firstRow, $row, $fileName, $fileLength); // Prevent timeouts on slow networks/large files set_time_limit(0); // Place the file pointer back at the beginning rewind(tmpFP); // Serve the file download fpassthru($tmpFP); // Close the file pointer fclose($tmpFP); // ...and we're done exit;