Tutorials, PHP & MySQL

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

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

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.