通过 php 生成管道分隔文件


Generate pipe delimited file through php

我的代码使用 PHP 的 fputcsv 函数生成一个 txt 文件。

对于分隔符,我正在尝试使用"|"

$query = mysql_query("SELECT email, emailSource FROM session WHERE is_complete='1' ORDER by sessionid ASC")
$filename= 'here.txt';
$fp = fopen( $filename,'w');

fputcsv($fp, array('Email address', 'Email Source'));
if(mysql_numrows($query) > 0) {
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
            fputcsv($fp, array_values($row));
    }
}

fclose($fp);
$contents = file_get_contents($filename);
$contents = str_replace(",", "|", $contents);
file_put_contents($filename, $contents);

我得到的结果都在一行上,而不是在单独的行上显示值,而且标题周围也有"。

"Email address"|"Email Source"|blah@blah.com|hi|

取而代之的是:

Email address|Email Source|
blah@blah.com|hi|

请有人告诉我我做错了什么。是因为我正在使用 fputcsv 并保存到 txt 文件吗?

摆脱str_replace/file_get_contents/file_put_contents块。代替fputcsv($fp, array('...')),使用fputcsv($fp, array('...'), '|');