使用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']));
?>
Run Code Online (Sandbox Code Playgroud)
如果我加载$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写入行尾?
Tim*_*per 10
\r\n需要将其括起来,"而不是'解释转义序列(参见文档):
$linkstring .= $i.','.$url['ID'].','.$url->TITLE.','.$url->URL."\r\n";
Run Code Online (Sandbox Code Playgroud)
在网上浏览后,我发现问题是由于未启用“自动检测行结束”功能。只需在您的代码上设置它,它就可以工作。它为我工作。
ini_set('auto_detect_line_endings',TRUE);
Run Code Online (Sandbox Code Playgroud)
启用auto_detect启用后,您可以使用以下命令将文件解析为常规文件
$lines = file('your_csv_file.csv');
Run Code Online (Sandbox Code Playgroud)
就我而言,我已经使用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;
}
Run Code Online (Sandbox Code Playgroud)