PHP csv文件的行结束字符


PHP end of line character for a csv file

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

<?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.com1 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需要包含在"而不是'中,以便转义序列将被解释(参见文档):

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

在整个web上查看后,我发现问题是由于自动检测行结束未启用。只要在你的代码中设置它,它就会工作。这对我很有效。

ini_set('auto_detect_line_endings',TRUE);

启用auto_detect后,您可以使用

将文件解析为常规文件
$lines = file('your_csv_file.csv');

在我的情况下,我已经使用str_getcsc解析CSV行

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;
}