在PHP中重新格式化文本文件

时间:2014-07-05 17:19:06

标签: php csv

我有一个文本文件text.txt,日期安排如下。

name1
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name2
2010-01-02 (i)
2010-05-07 (i)
2010-06-12 (i)
name3
2011-01-05 (i)
2011-05-05 (i)
2011-06-14 (i)

我想把文件写成两列,如:

+---------------+-----+
| 2010-01-02 (i)|name1|
| 2010-05-07 (i)|name1|
| 2010-06-12 (i)|name1|  
| 2010-01-02 (i)|name2|
| 2010-05-07 (i)|name2|
| 2010-06-12 (i)|name2|
| 2011-01-05 (i)|name3|
| 2011-05-05 (i)|name3|
| 2011-06-14 (i)|name3|
+---------------+-----+

此代码未按预期创建文件。

<?php
$path = "text.txt";
$file = file($path);
foreach($file as $value)
{
  $name = "";
  // if ( is found
  if ( strpos($value, "(" ) !== false)
  {
    $date = $value;
    $line = $date . "|" . $name;
    $val = explode("|",$line);
    //write only
    $fp = fopen('data.csv', 'w');
    fputcsv($fp, $val);
    fclose($fp);
  }
  else
  {
    $name = $value;
    //echo $name . "<br />";
  }
}
?>

2 个答案:

答案 0 :(得分:1)

$path = "text.txt";
$file = file($path);

$fp = fopen('data.csv', 'w+');
$title = array_shift($file);

foreach($file as $value) {
    if (!strpos($value, "(" )){
        $title = $value;
    }
    else {
        $data = array_map('trim', array($value, $title));
        fputcsv($fp , $data, '|');
    }
}
fclose($fp);

答案 1 :(得分:0)

在这里,你可以试试这个:

<?php
$path = "text.txt";
$file = file($path);
$outputFile = 'data.csv';

$datein = '1998-09-21';
if(preg_match('/^\d{4}-\d{2}-\d{2}\s\(i\)$/', $datein)){
    echo 'go';
}else{
    echo 'no go';
}

$fp = fopen($outputFile,'w');

$name = "";
foreach($file as $value)
{


  // match a date-line
  if(preg_match('/^\d{4}-\d{2}-\d{2}\s\(i\)$/', $value)) {

     $line = trim(preg_replace('/\s+/', ' ', $value)) . "|" . $name;
     fwrite($fp,$line);
  } else {

      $name = $value;
  }
}
fclose($fp);
?>

请注意,我将$name = '';移到了循环之外,并将其更改为使用正则表达式。 trim(preg_replace...函数用于删除读取行并将其存储到数组中时自动出现的换行符。