Open In App

How to download a CSV file in PHP that is triggered through a URL ?

Improve
Improve
Like Article
Like
Save
Share
Report

Why do we need to download CSV files?
Comma-Separated Values or CSV files are an important part of computer science. Almost every dataset required for training data science models are in CSV file format. Datasets are available all over the internet and it becomes the utmost necessity to have them readily on one’s machine be it someone’s personal computer or on a server. On the server end, one can train his or her web models with various data sets easily if the person can develop a server-side system to easily download a CSV file on the server via any URL pointing to a data set.

How we can download CSV files triggered through a URL?
Downloading a CSV file through a URL is very easy with PHP and we will discuss here how to achieve that to download a CSV file on both server end and client end.

For server end download:

To achieve this, we need a PHP function file_get_contents(). This is an inbuilt PHP function that reads the contents of a file in a string type. The function uses a memory mapping technique with a cache on the server end. Hence, this is a preferable choice for our very purpose.

Syntax:

file_get_contents($path, $include_path, 
        $context, $start, $max_length)

Parameters: The function has got one mandatory parameter which the $path and the rest are optional.

  • $path: It holds the path or the URL of the file concerned.
  • $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1.
  • $context: It is used to specify a context.
  • $max_length: It is used to restrict the bytes to be read.

Return Value: Returns back the read data from the file or False if the process is failure.

Example 1: The simple example demonstrates how a CSV file can be downloaded on the server end with the file_get_contents() function.




<?php
  
// Initialize a file URL to the variable 
$url = 'Sample-Spreadsheet-10-rows.csv';  
  
// Use basename() function to return
// the base name of file  
$file_name = basename($url); 
      
// Checking if the file is a
// CSV file or not
$info = pathinfo($file_name);
  
if ($info["extension"] == "csv") {
      
    /* Use file_get_contents() function
    to get the file from url and use 
    file_put_contents() function to save
    the file by using base name */   
    if(file_put_contents( $file_name
            file_get_contents($url))) { 
        echo "File downloaded successfully";
    }
    else
        echo "File downloading failed."
    }
}
else echo "Sorry, that's not a CSV file";
  
?>


Output:
The response the browser will show on successful execution.
csv file download in php

The file downloaded in the server directory.
csv file download in php

For client end download: Forcing a CSV file on the client end through PHP is cakewalk with a PHP inbuilt function called readfile() method. The function reads a file and passes it to the output buffer.

Syntax:

readfile($filename, $include_path, $context)

Parameters:

  • $filename: The name of the file to be read.
  • $include_path: It searches for a file in the include_path (in php.ini) if the value is set to 1.
  • $context: It is used to specify a context.

Return Value: On success returns the number of bytes read, else it returns False.

Example 2: The simple following program demonstrates downloading csv file on client end machine with the use of readfile() function.




<?php
  
$url = "Sample-Spreadsheet-10-rows.csv";
  
echo "Your file is being checked. <br>";
  
// Use basename() function to return
// the base name of file
$file_name = basename($url); 
  
$info = pathinfo($file_name);
  
// Checking if the file is a
// CSV file or not
if ($info["extension"] == "csv") {
  
    /* Informing the browser that
    the file type of the concerned
    file is a MIME type (Multipurpose
    Internet Mail Extension type).
    Hence, no need to play the file
    but to directly download it on
    the client's machine. */
    header("Content-Description: File Transfer"); 
    header("Content-Type: application/octet-stream"); 
    header(
    "Content-Disposition: attachment; filename=\""
    . $file_name . "\""); 
    echo "File downloaded successfully";
    readfile ($url);
  
else echo "Sorry, that's not a CSV file";
   
exit(); 
  
?>


Output:
csv file download in php



Last Updated : 11 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads