1

所以我有一个 CSV 文件,其中的行如下所示:

126404 "560-00877" "中心盖,A 级,灰色," 877 2 34.29 0

我想添加一个时间戳列,使它们看起来像这样:

126404 "560-00877" "中心盖,A 级,灰色," 877 2 34.29 0 2005-04-06

是否有一种简单的(r) php 方法可以打开 CSV 文件并将时间戳附加到每一行?

谢谢!

4

4 回答 4

0

您可以将文件的每一行读入一个数组,并在写回时将时间戳附加到每一行:

$filename="/path/to/file.txt";

// Backup
if(!copy($filename, 'backup.txt')){
    die('Failed to backup!');
}

// Store file contents in array
$arrFile = file($filename);

// Open file for output
if(($fp = fopen($filename,'w')) === FALSE){
    die('Failed to open!');
}

// Write contents, inserting $data as second line
$currentLine = 0;
$cntFile = count($arrFile);
while( $currentLine <= $cntFile ){
    fwrite($fp, $arrFile[$currentLine].",".date('y-m-d').",\n");
    $currentLine++;
}

// Delete backup
unlink('backup.txt');

只需修改行date('Y-M-D')以适合您的需要。

于 2012-06-06T10:37:24.563 回答
0

这个?

$data = file("file.csv",FILE_IGNORE_NEW_LINES);
$fp = fopen("file_new.csv","w");
foreach((array)$data as $val) {
   fwrite($fp,$val." ".$timestamp."\r\n");   // build the $timestamp   
}
fclose($fp);
于 2012-06-06T10:43:40.413 回答
0

与标准函数最接近的是使用 fgetcsv/fputcsv 为您执行解析/转义工作:

$hSrc = fopen('path/to/file.csv', 'o');
if ($hSrc === false) {
    throw new Exception('Cannot open source file for reading!');
}

$hDest = fopen('path/to/new.csv', 'w');
if ($hDest === false) {
    throw new Exception('Cannot open destination file for writing!');
}

$timestamp = date('Y-m-d');

// reading source file into an array line by line
$buffer = 1000; // should be enough to accommodate the longest row
while (($row = fgetcsv($hSrc, $buffer, ' ')) !== false) {
    $data['timestamp'] = $timestamp;

    // writing that modified row into a new file
    if (fputcsv($hDest, $data, ' ') === false) {
        throw new Exception('Failed to write a CSV row!');
    }
}

fclose($hDest);
fclose($hSrc);
于 2012-06-06T10:51:31.913 回答
0

我会这样做:

<?php
$file_path = "yourfile.txt";
$file = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file as $line => $content)
{
    $file[$line] = $content." ".date('Y-m-d');
}
$file = implode("\n",$file);
file_put_contents($file_path, $file);
?>
于 2012-06-06T10:59:35.107 回答