csv文件的PHP行尾字符

问题描述:

什么是用PHP指定CSV文件的行尾字符的正确方法。我有这个脚本来编写CSV文件。csv文件的PHP行尾字符

<?php 

ini_set('display_errors', 1); 
error_reporting(E_ALL); 

include_once("phpshared.php"); 

function get_node_urls($nodeid) { 

$nodes = new SimpleXMLElement('linkcards.xml', null, true); 
$nodesarray = $nodes->xpath("//LINKCARD[@ID='$nodeid']"); 

$linkstring = ''; 
$node = $nodesarray[0]; 
$i = 0; 
foreach($node->LINKS->LINK as $url) 
{ 
     $linkstring .= $i.','.$url['ID'].','.$url->TITLE.','.$url->URL.'\r\n'; 
     $i++; 
} 
echo $linkstring; 

} 

echo get_node_urls(trim($_REQUEST['nodeid'])); 

?> 

如果我加载$linkstring在每行末尾没有回车符。该行应该是:

 
0, id1, http://link1.com 
1, id2, http://link2.com 

相反,它们是:

 
0, id1, http://link1.com\r\n1, id2, http://link2.com 

的CSV阅读器读取行:

 
id1 http://link1.com\r\n1 

是否有写行的末尾以不同的方式一个CSV?被封闭在"代替'使转义序列

\r\n需求将被解释(see documentation):

$linkstring .= $i.','.$url['ID'].','.$url->TITLE.','.$url->URL."\r\n"; 
+0

+1这已经解析CSV行是正确的答案 –

+0

太棒了!这工作。谢谢。 – user823527

+0

+1 Arrggghhhh!非常感谢,在PHP中处理行结束是绝对荒谬的。 – demongolem

看所有网站上后,我发现,这个问题是由于自动侦测行结束不被启用。只需将它设置在你的代码上,它就可以工作。它为我工作。

ini_set('auto_detect_line_endings',TRUE); 

随着auto_detect使您可以使用

$lines = file('your_csv_file.csv'); 

在我的情况下解析该文件为常规文件我用str_getcsc

function parse_my_csv($filename) { 
    $lines = file($filename); 
    $data = array(); 
    for($i=0;$i<count($lines);$i++) { 
     array_push($data, str_getcsv($lines[$i])); 
    } 
return $data; 
}