【问题标题】:PHP end of line character for a csv filecsv文件的PHP行尾字符
【发布时间】:2014-10-09 09:19:07
【问题描述】:

用 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.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 的行尾?

【问题讨论】:

    标签: php csv


    【解决方案1】:

    \r\n 需要包含在 " 而不是 ' 中,以便解释转义序列 (see documentation):

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

    【讨论】:

    • +1 啊啊啊啊!非常感谢,PHP 中的行尾处理绝对是可笑的。
    【解决方案2】:

    查看整个网络后,我发现问题是由于未启用自动检测行尾。只需在您的代码上设置它,它应该可以工作。它对我有用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多