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

时间:2018-11-08 13:14:01

标签: php csv file-get-contents php-7 file-handling

我有一个CSV文件,其中希望删除前11行。该文件如下所示:

ec2-user@ip-10-14-6-40 ~]$ sudo yum install docker -v
Loading "langpacks" plugin
Not loading "priorities" plugin, as it is disabled
Loading "update-motd" plugin
Adding en_US to language list
Config time: 0.007
Yum version: 3.4.3
rpmdb time: 0.000
Setting up Package Sacks
pkgsack time: 0.010
Checking for virtual provide or file-provide for docker
Checking for installed virtual provide or file-provide for docker
No package docker available.
Error: Nothing to do

我只想要股票数据,而没有别的东西。因此,我希望删除前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 似乎不是一个可行的选择。我一直用于获取CSV文件并将所需内容放入文本文件的功能是

str_replace

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

3 个答案:

答案 0 :(得分:2)

这里的每个示例都不适用于大文件/大文件。如今人们不关心内存。作为一名优秀的程序员,您希望代码效率高,内存占用少。

代替逐行解析文件:

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) {
            ++$counter;
            continue;
        }

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

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

答案 1 :(得分:1)

  

我有一个CSV文件,我希望在其中删除前11行。

我总是喜欢使用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从中创建一个新的“文件”

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

$new将包含新文件

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

请注意!!我会引用@emix他的评论。

  

如果文件内容超出了可用的PHP内存,这将严重失败。

确保文件不会“过大”

答案 2 :(得分:0)

使用file()将其读取为数组,只需修剪前11行:

$content = file($url);

$newContent = array_slice($content, 12);

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

但是请回答以下问题:

  1. 为什么此CSV中还有其他内容?
  2. 您如何知道要切断多少行?如果要剪切多于11行怎么办?