Sitemap / Advertise

Information



Tags



Share

How to create a CSV file and upload it automatically to the client-server in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to create a CSV (Comma-separated values) file using the data string entered by the user in PHP. In addition to that, you will learn how to upload a file to the client-server without any triggered event in PHP.

You can inspect a web application named CSV File Creator, that utilizes the same method, from the link below. Please sign in before inspecting the mentioned application.

Go to CSV File Creator.

What is a CSV file?(1)

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. A CSV file typically stores tabular data (numbers and text) in plain text, in which case each line will have the same number of fields.

The CSV file format is not fully standardized. The basic idea of separating fields with a comma is clear, but that idea gets complicated when the field data may also contain commas or even embedded line breaks. CSV implementations may not handle such field data, or they may use quotation marks to surround the field. Quotation does not solve everything: some fields may need embedded quotation marks, so a CSV implementation may include escape characters or escape sequences.

In addition, the term "CSV" also denotes some closely related delimiter-separated formats that use different field delimiters, for example, semicolons. These include tab-separated values and space-separated values. A delimiter that is not present in the field data (such as tab) keeps the format parsing simple. These alternate delimiter-separated files are often even given a .csv extension despite the use of a non-comma field separator. This loose terminology can cause problems in data exchange. Many applications that accept CSV files have options to select the delimiter character and the quotation character. Semicolons are often used in some European countries, such as Italy, instead of commas.

Code

- Define a function named createCSV() with two variables - data_string and name.

- Define the file name with the .csv extension.

- Define the file path in the server to create a temporary file: in this case, I used the same directory.

- Using the preg_split() function, separate each row when a new line character is detected - \r\n.

- Create a file using the fopen() function with the file name in writing mode -w.

- For each detected row, create a new line using the fputcsv() function.

- In the fputcsv() function, to generate columns for each row, separate each variable divided by a comma using the explode() function.

- To close the file writing mode, use the fclose() function.

- To upload the recently generated file to the client-server, define the header parameters - Content-Description, Content-Type, Content-Length, Content-Disposition- and, subsequently, execute the readfile() function with the file name.

- To avert any disruption by the user, use the ignore_user_abort(true) function.

- Delete the recently generated file after uploading it to the client-server by executing the unlink() function with the file path.

- Get the data string entered by the user: in this case, I pre-defined the data string.

- Activate the createCSV() function.

Note: You can execute the exact code by clicking the Try button below to test the mentioned function.



<?php
    function createCSV($data_string, $name){
		$file_name = $name.".csv";
		$file_path = $file_name;
		$entry = preg_split('/\r\n|\r|\n/', $data_string, -1, PREG_SPLIT_NO_EMPTY);
		
		$file = fopen($file_name, 'w');
		foreach($entry as $row){
			fputcsv($file, explode(',', $row));
		}
		fclose($file);
		
		header('Content-Description: CSV File');
        header('Content-Type: application/csv');
		header('Content-Length: ' . filesize($file_path));
        header('Content-Disposition: attachment; filename="'.$file_name);
        readfile($file_name);
		
		ignore_user_abort(true);
		unlink($file_path);
		exit();
	}
	
	$user_data = "
	      BMV, 123, John 
	      Audi, 124, Mark
		  Chevrolet, 126, Emma
		  Renault, 127, Tessa
	";
	
	createCSV($user_data, "test");
	
?>
	

Result:

References

(1) https://en.wikipedia.org/wiki/Comma-separated_values