2010-04-08 60 views
0

我使用通用算法编写理论上适用于主要操作系统的CSV文件。但是,客户在几周前开始使用Mac,他们一直告诉我在Microsoft Excel 2008 for Mac 12.2.1中无法读取CSV文件。使用PHP为Mac用户编写CSV文件

他们的操作系统配置为使用“分号”作为列表分隔符,这正是我在CSV中编写的内容。他们还说,当他们在记事本中打开文件时,他们已经注意到没有换行符,所有内容都显示在一行中;这就是为什么Excel无法正确读取文件的原因;但在我的代码,我现在用的是跨浏览器的断行\r\n

这是一个完整的代码,我使用:

header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
// Output to browser with appropriate mime type, you choose ;) 
header("Content-type: text/x-csv"); 
//header("Content-type: text/csv"); 
//header("Content-type: application/csv"); 
header("Content-Disposition: attachment; filename=participantes.csv"); 

$separator = ";"; 
$rs = $sql->doquery("SELECT A QUERY TO RETRIEVE DATA FROM THE DB"); 

$header = ""; 
$num_fields = mysql_num_fields($rs); 

for($i=0; $i<$num_fields; $i++){ 
    $field = mysql_field_name($rs, $i); 
    $header .= $field.$separator; 
} 

echo $header."\r\n"; 

while($row = $sql->fetch($rs)){ 
    $str = ""; 
    for($i=0; $i<$num_fields; $i++){ 
    $field = mysql_field_name($rs, $i); 
    $value = str_replace(";", ",", $row->{$field}); 
    $value = str_replace("\n", ",", $value); 
    $value = str_replace("\d", ",", $value); 
    $value = str_replace(chr(13), ",", $value); 
    $str .= $value.$separator; 
    } 
    echo $str."\r\n"; 
} 

有什么我可以这样做,Mac用户可以正常读取文件?

+0

你试过用第三个替换第一个头选项吗? – pnuts 2015-05-31 02:20:19

回答

1

调试目的:

  1. 创建一个CSV文件,并通过邮件发送给他们。他们可以打开它吗?
  2. 让他们从您的页面下载文件并将其发回给您。使用十六进制编辑器对文件进行比较,以排除它们与发送给浏览器或您保存的内容不一致的可能性。
  3. 让他们仔细检查他们的Excel设置。
  4. 让他们从头开始创建一个可用的CSV文件(Mac上的文本编辑器),并发现与您的方法有所不同。
0

下面是一些代码,我将标签分隔的数据转换为CSV,并且它在我的Mac上很好。请注意,我已经设置好了让我点击下载,而不是将它推送到浏览器。这不是一个很好的解决方案(我敢肯定代码是垃圾),但它适用于我需要的。

$input = $_POST['input']; 
//Remove commas. 
$replacedinput1 = str_replace(",", "-", $input); 
//remove tabs, replace with commas 
$replacedinput2 = str_replace(" ", ",", $replacedinput1); 
//create an array 
$explodedinput = explode(" 
", $replacedinput2); 
//open the CSV file to write to; delete other text in it 
$opencsvfile = fopen("/var/www/main/tools/replace_tab.csv","w+"); 
//for each line in the array, write it to the file 
foreach($explodedinput as $line) { 
fputcsv ($opencsvfile, split(',', $line)); 
}; 
//close the file 
fclose($opencsvfile); 
//have the user download the file. 
/* 
header('Pragma: public'); 
header('Expires: Fri, 01 Jan 2010 00:00:00 GMT'); 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Content-Type: application/csv'); 
header('Content-Disposition: filename=replace_tab.csv'); */ 

//Or not, since I can't get it to work. 
echo "<a href='replace_tab.csv'>Download CSV File, then open in Numbers or Excel (Note, you may need to right click, save as.)</a>."; 
0

Mac中的换行符是LF(unicode U + 000A),在Windows中是CR + LF(Unicode U + 000D后跟U + 000A)。

也许这就是为什么csv在Mac上无法读取的原因。