如何使用 PHP 删除文件中的前 11 行?

How to delete first 11 lines in a file using PHP?

我有一个 CSV 文件,我想删除其中的前 11 行。该文件类似于:

"MacroTrends Data Download"
"GOOGL - Historical Price and Volume Data"
"Historical prices are adjusted for both splits and dividends"

"Disclaimer and Terms of Use: Historical stock data is provided 'as is' and solely for informational purposes, not for trading purposes or advice."
"MacroTrends LLC expressly disclaims the accuracy, adequacy, or completeness of any data and shall not be liable for any errors, omissions or other defects in, "
"delays or interruptions in such data, or for any actions taken in reliance thereon.  Neither MacroTrends LLC nor any of our information providers will be liable"
"for any damages relating to your use of the data provided."


date,open,high,low,close,volume
2004-08-19,50.1598,52.1911,48.1286,50.3228,44659000
2004-08-20,50.6614,54.7089,50.4056,54.3227,22834300
2004-08-23,55.5515,56.9157,54.6938,54.8694,18256100
2004-08-24,55.7922,55.9728,51.9454,52.5974,15247300
2004-08-25,52.5422,54.1672,52.1008,53.1641,9188600

我只想要股票数据,不需要其他任何东西。所以我想删除前 11 行。此外,将有多个文本文件用于不同的代码。所以 str_replace 似乎不是一个可行的选择。我用来获取 CSV 文件并将所需内容放入文本文件的函数是

 function getCSVFile($url, $outputFile)
    {
        $content = file_get_contents($url);
        $content = str_replace("date,open,high,low,close,volume", "", $content);
        $content = trim($content);
        file_put_contents($outputFile, $content);
    }

我想要一个通用的解决方案,它可以从 CSV 文件中删除前 11 行并将其余内容放入文本文件。我该怎么做?

I have a CSV file in which I want the first 11 lines to be removed.

我总是喜欢使用 explode 来做到这一点。

$string = file_get_contents($file);
$lines = explode('\n', $string);
for($i = 0; $i < 11; $i++) { //First key = 0 - 0,1,2,3,4,5,6,7,8,9,10 = 11 lines
    unset($lines[$i]);
}

这将删除它并使用 implode 您可以从中创建一个新的 'file'

$new = implode('\n',$lines);

$new 将包含新文件

没有测试,但我很确定这会起作用

小心! 我会引用@emix 他的评论。

This will fail spectacularly if the file content exceeds available PHP memory.

确保该文件不是 'huge'

使用 file() 将其作为数组读取并简单地 trim 前 11 行:

$content = file($url);

$newContent = array_slice($content, 12);

file_put_contents($outputFile, implode(PHP_EOL, $newContent));

但请回答这些问题:

  1. 为什么这个 CSV 中有额外的内容?
  2. 你怎么知道要剪掉多少行?如果超过 11 行要剪切怎么办?

此处的每个示例都不适用于 large/huge 个文件。现在人们不在乎记忆。作为一名优秀的程序员,您希望您的代码高效且内存占用少。

改为逐行解析文件:

function saveStrippedCsvFile($inputFile, $outputFile, $lineCountToRemove)
{
    $inputHandle = fopen($inputFile, 'r');
    $outputHandle = fopen($outputFile, 'w');

    // make sure you handle errors as well
    // files may be unreadable, unwritable etc…

    $counter = 0;
    while (!feof($inputHandle)) {
        if ($counter < $lineCountToRemove) {
            fgets($inputHandle);
            ++$counter;
            continue;
        }

        fwrite($outputHandle, fgets($inputHandle) . PHP_EOL);
    }

    fclose($inputHandle);
    fclose($outputHandle);
}