提问者:小点点

CSV到php,file()在新行中创建额外dubbel引号,


只是用HTML表单和PHP建立一个简单的访客簿。 我将名称,消息和时间保存在数组中。 然后转到CSV文件。

当我读取csv-文件时,问题就开始了。 问题是file()函数会在开头和结尾添加额外的引号。 最后一句引用出现在新的一行。 这些引号仅在var_dump()中可见。 会产生一个空行。

功能:

// READ CSV FILE
public function readcsv($filename) {
    $rows = array();
    $fh = fopen($filename, "r");
    foreach (file($fh, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        //$newline = str_replace('""', "", $line);
        //$newline = trim(html_entity_decode($newline),'"');
        $newline = preg_match('/^[a-öA-Ö0-9]{2,12}$/', $line);
        $rows[] = str_getcsv($newline);
    }

    return $rows;
    //close the file
    fclose($fh);
}

我已经尝试了str_replace(),trim(html_entity_decode()和preg_match.我只是不能让它工作。结果仍然如下:print_r()=

    Array
(
    [0] => Peter,"test message one","2020-07-04: 14.40"

    [1] => Bjorn,"test number 2","2020-07-04: 14.40"

    [2] => Nina,"Test number 3","2020-07-04: 14.40"
)

和var_dump()=

    array(3) {
  [0]=>
  string(45) "Peter,"test message one","2020-07-04: 14.40"
"
  [1]=>
  string(42) "Bjorn,"test number 2","2020-07-04: 14.40"
"
  [2]=>
  string(41) "Nina,"Test number 3","2020-07-04: 14.40"
"}

有人有解决办法吗?


共1个答案

匿名用户

如果您有一个非常简单的CSV源文件(根据您的问题)--为了便于下面的PHP,我将其命名为GB.CSV,并将其存储在与测试脚本相同的目录中。

Peter,"This is a test message","2020-07-01: 11.20"
Rita,"This is a fantastic feature...","2020-07-04: 14.40"
Susan,"Wowser... what wonders next I wonder","2020-06-02: 14.42"

使用对原始文件稍作修改的版本

function readcsv( $filename ) {
    $rows = array();
    $data = file( $filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
    foreach( $data as $line ) {
        $rows[] = str_getcsv( $line );
    }
    return $rows;
}


$arr=readcsv( 'gb.csv' );
printf( '<pre>%s</pre>', print_r( $arr, true ) );

这将生成如下所示的多维数组:

Array
(
    [0] => Array
        (
            [0] => Peter
            [1] => This is a test message
            [2] => 2020-07-01: 11.20
        )

    [1] => Array
        (
            [0] => Rita
            [1] => This is a fantastic feature...
            [2] => 2020-07-04: 14.40
        )

    [2] => Array
        (
            [0] => Susan
            [1] => Wowser... what wonders next I wonder
            [2] => 2020-06-02: 14.42
        )

)