简体   繁体   English

将时间戳列添加到预先存在的csv

[英]Adding timestamp column to pre-existing csv

So I've got a CSV file with rows that look like this: 所以我有一个CSV文件,其中的行如下所示:

126404 "560-00877" "CENTER CAP,GRADE A,GRAY," 877 2 34.29 0 126404“ 560-00877”“中心盖,灰色,A” 877 2 34.29 0

I'd like to add a time stamp column so they look like this: 我想添加一个时间戳列,使它们看起来像这样:

126404 "560-00877" "CENTER CAP,GRADE A,GRAY," 877 2 34.29 0 2005-04-06 126404“ 560-00877”“中心盖,A级,灰色,” 877 2 34.29 0 2005-04-06

Is there a simple(r) php method of opening the CSV file and appending a timestamp to each row? 有没有简单的PHP方法来打开CSV文件并将时间戳添加到每一行?

Thanks! 谢谢!

You could read each line of the file into an array, and append the time stamp to each line when you write it back: 您可以将文件的每一行读入一个数组,并在回写时将时间戳添加到每一行:

$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');

Just modify the line with date('YM-D') to fit your needs. 只需修改date('YM-D')即可满足您的需求。

this one? 这个?

$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);

The closest you can get with standard functions is using fgetcsv/fputcsv which do the parsing/escaping job for you: 使用标准函数可以获得的最接近的结果是使用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);

I would do this: 我会这样做:

<?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);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM