回车和换行

时间:2016-12-13 06:48:45

标签: php carriage-return file-writing linefeed

我遇到了回车和换行问题。当我运行我的脚本时,它显示CR,LF在最后一个字段的双引号内,并且还有另一个LF,实际上CR,LF应该在文本的双引号之外,并且不应该是另一个LF。有人能告诉我我做错了什么吗?

这是我的代码

$jobno = 5285;

$directory = "../CSV/";
$filename = $jobno.'.csv';
if( is_dir($directory) === false )
{
   mkdir($directory); // Create new directory 

}
$newFname = $directory.$filename;

$file = fopen($newFname, 'w');


$jobdetails="2,000 Items Supplied";
$customerName="Snap Pitzaa Ltd";
$workflow="CSV_wise";
$jobqty=50;
$filepath="Data/Snap Pitzaa/design.pdf \r\n";

$data = array(
    array($jobno, $jobdetails, $customerName, $workflow, $jobqty, $filepath),
    array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25', 'Data 26'),

);

// save each row of the data
foreach ($data as $row)
{
    fputcsv($file, $row);
}

// Close the file
fclose($file);

我已经尝试了所有的事情,比如单引号,$filepath的外部双重标题,但这些都没有效果。这是输出在notepad ++

enter image description here

2 个答案:

答案 0 :(得分:1)

fputcsv以换行符(here)终止。因此,您无需将\r\n添加到$filepath变量。

此:

$filepath="Data/Snap Pitzaa/design.pdf \r\n";

应改为:

$filepath='Data/Snap Pitzaa/design.pdf';

这应该删除“CRLF”并将报价移动到您想要的位置。

编辑12/13/16

从您的评论中,您可能需要替换fputcsv默认输出的带有Windows样式行结尾的unix样式行结尾。我见过的最优雅的方式来自docs

// Writes an array to an open CSV file with a custom end of line.
//
// $fp: a seekable file pointer. Most file pointers are seekable, 
//   but some are not. example: fopen('php://output', 'w') is not seekable.
// $eol: probably one of "\r\n", "\n", or for super old macs: "\r"
function fputcsv_eol($fp, $array, $eol) {
  fputcsv($fp, $array);
  if("\n" != $eol && 0 === fseek($fp, -1, SEEK_CUR)) {
    fwrite($fp, $eol);
  }
}

答案 1 :(得分:0)

刚刚给自己介绍了PHP(我之前从未使用过),我认为以下代码会正确地将CR / LF写入您编写的每条记录的末尾:

foreach ($data as $row)
{
    // write out the normal output, with a LF automatically created by fputcsv
    fputcsv($file, $row);
    // move the file pointer back to the end of the data
    fseek($file, -1, SEEK_CUR); 
    // write out a CR/LF
    fwrite($file, "\r\n");
}

您还应该更改

$filepath="Data/Snap Pitzaa/design.pdf \r\n";

$filepath="Data/Snap Pitzaa/design.pdf";

因为该字段中不应有CR / LF