所以我有一个CSV文件,其行如下所示:
126404“560-00877”“CENTER CAP,A级,灰色,”877 2 34.29 0
我想添加一个时间戳列,使它们看起来像这样:
126404“560-00877”“CENTER CAP,A级,灰色,”877 2 34.29 0 2005-04-06
是否有一个简单的(r)php方法打开CSV文件并在每一行附加时间戳?
谢谢!
答案 0 :(得分: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')
修改该行即可满足您的需求。
答案 1 :(得分: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);
答案 2 :(得分: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);
答案 3 :(得分: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);
?>