dongyuan1984 2019-04-27 18:02
浏览 125
已采纳

从文本文件中获取数据并存储输出PHP

I have a test.txt text file with the following contents:

Test Data: some text
Tester 2 Data: some other text
Tests 3 Data: some more

When I run this through my PHP file:

$raw = file("./test.txt");
$lineCount = count($raw);
$newFile = null;
do {
    $newFile .= "Data:
";
} while(--$lineCount > 0);
file_put_contents('./test-new.txt',trim($newFile));

I get this:

Data: 
Data: 
Data: 

My preferred output would be:

Data: some text
Data: some other text
Data: some more

What changes do I need to make to my script to get this result?

  • 写回答

1条回答 默认 最新

  • douxiong4250 2019-04-27 18:13
    关注

    The following code snippet will read the file line by line and put the string after :

    $fn = fopen("./test.txt","r");
    while(! feof($fn))  {
      $line = fgets($fn);
      $line = 'Data : '.substr($line, strpos($line, ':')+1, strlen($line));
      echo $line;
      echo '<hr>';
    }
    fclose($fn);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?