Search code examples
phpcsvfile-get-contentsphp-7file-handling

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


I have a CSV file in which I want the first 11 lines to be removed. The file looks something like:

"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

I want only the stocks data and not anything else. So I wish to remove the first 11 lines. Also, there will be several text files for different tickers. So str_replace doesn't seem to be a viable option. The function I've been using to get CSV file and putting the required contents to a text file is

 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);
    }

I want a general solution which can remove the first 11 lines from the CSV file and put the remaining contents to a text file. How do I do this?


Solution

  • Every example here won't work for large/huge files. People don't care about the memory nowadays. You, as a great programmer, want your code to be efficient with low memory footprint.

    Instead parse file line by line:

    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);
    }