Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Collect remote CSV file and save to a local CSV file using PHP

David Carr

PHP & MySQL Tutorials

    Here is a quick way to read a csv file hosted remotely, download its contents and store it to a local csv file. Once the file have been saved open the file loop through the data and display it. Equally this can be used to import data into a database.

    Perfect for a daily task by calling the script with a cron job.

    //collect the remote csv file
    $csv = file_get_contents('https://domain.com/records.csv');
    
    //save the data to a local csv file
    file_put_contents('data.csv', $csv);
    
    //open the local csv file
    $handle = fopen('data.csv', "r");
    
    //loop through the records
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        for ($c=0; $c < 1; $c++) {  
    
            //view the data 
            print_r($data);
            
        }    
    }
    
    //close the file
    fclose($handle);

     

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.