The comma-separated values (CSV) file format is the most widely supported means of representing tabular data. Including a CSV export feature in a web application allows its data to be processed by other applications, increasing its value to users. Show
Lines 1 and 2 output HTTP headers declaring that the content is UTF-8-encoded CSV data
and that the browser should offer to download it. The Line 4 creates a file pointer that can be used to write to the
PHP output stream, and then lines 5 and 6 use the
Lines 7 to 11 query the database for the list of users. The by Vincy. Last modified on July 12th, 2022. CSV is one of the familiar file formats and used widely by programmers for handling data. The simplicity of the format and human readable form made it so popular. CSV stands for Comma-Separated Values. In earlier days, the delimiter was only a comma (,) and so the name CSV. Nowadays, CSV files use tab-demitted row data too. To handle CSV with PHP, we must be aware there is excellent support in-built with core PHP. Knowledge about those built-in library and functions will he handy in handling CSV files. What is inside?In this article, we will see about about how to handle CSV using PHP with suitable examples.
This will serve you as a comprehensive tutorial that discusses all aspects of CSV file handling with PHP. When you need to handle structured data then using JSON data and handling it with PHP will be a better choice. CSV file format and MIME typeLet us start with CSV format and MIME type conventions. The common formats and MIME type for the CSV files are discussed here with the reference of the RFC 4180 documentation. CSV Format DefinitionThese are the general definitions for a valid CSV format.
The standard exclusive MIME type text/csv is registered by the RFC 4180. Before that, various MIME types like “text/tab-separated-values” type were used by various programs or OS for the CSV format. If you want to learn more about the CSV format and MIME types, the RFC 4180 document has more information. How to convert PHP Array to CSV?There are many possible ways in PHP to convert an array data into CSV format. PHP contains in-built functions like fputcsv() for doing this conversion. The following code uses custom PHP function str_putcsv() to get the array data and put it into the file target as specified. This custom function uses PHP built-in fputcsv() on each array iteration.
I have printed the converted output data to the browser. The CSV output is, CSV file data validationGenerally, validation on a CSV file will be done to check whether it has the standard format definition. The following conditions have to be applied to a CSV input file to check whether it is valid or not.
Added to that, you can add additional validation based on your application requirement. For example,
This PHP code shows how to apply CSV validation on an uploaded file. In a previous tutorial, we have seen how to validate an uploaded image file in PHP. In this script, the validation made to check the CSV file extension, size. Once it is done, we need to handle CSV with PHP to check the field count in all the CSV rows.
CSV Validation Script
If the validation process is not returning TRUE then the error message will be displayed to the user as shown in the below screenshot. How to import large CSV files?Importing a large CSV file using PHP file handling functions may not be an efficient way of doing it. If the execution time exceeds the configured max_execution_time limit then the import will not be completed. While processing large CSV file import, there are ways like command line execution, query execution and more. In this section, I will show how to import a large CSV file using MySQL LOAD DATA statement. If you can this LOAD, then this is the better choice as it gives the best performance.
Before running this program, make sure that you have created the required target database and table. Import the following SQL script to process import by running this example in your environment.
Note: If the –secure-file-priv option is enabled in your MySQL configuration, then this program will work only if the input CSV file is located in the directory as specified in the –secure-file-priv settings. How to split large CSV files and process using PHP?In a previous tutorial, we have seen how to split an excel file into multiple files. Splitting will be required while dealing with large Excel or CSV file. In this section, I am showing how to split a CSV file into multiple files. I have used PHP RegexIterator and SplFileObject classes for implementing splitting on an input CSV file. The RegexIterator is the built-in PHP class that inherits FilterInheritor class to filter based on regular expression. It accepts the input data, regex pattern and mode of operations and more parameters. The SplFileObject class which gives an object-oriented interface for a file. Using this the target object is created to put the splitted records into the target.
How to read encoded CSV files with special characters?If the input CSV contains non-english data, the CSV file parsing will behave as expected. Either it will return error like “Invalid argument” or it will output jumbled character as the result of the CSV read operation. This issue could be resolved by setting the charset while reading CSV. In the below script, the PHP iconv function is used to set the input and output charset for reading the actual data from the CSV.
Convert CSV file to HTML table using PHPFor converting the CSV file into a HTML format, the table rows markup has to be created during the row by row iteration of the CSV. With the reference of the previous examples that we have seen above, it is an easy job to create HTML for the CSV data. Below code shows how to generate HTML table markup and display the CSV data into it. It iterates the CSV file uploaded via an HTML form and it is parsed to get the row data. The parsed row data is put into the table columns by using PHP echo statements. The table header could be identified by using the loop iteration index. Hence, the header data is differentiated from the other rows using CSS.
CSV to HTML Conversion OutputThe following screenshot shows the output of the HTML table generated by parsing the CSV file uploaded via the form. Process CSV file with comma data values using PHPAs per the CSV specification “Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes. So, I have created an input.csv containing values with Comma(,) character. The file content will be as shown as below.
In the above CSV data, you can see that the values containing Comma are enclosed by the double quotes(“) As like as the above example, we are going to use PHP fgetcsv() function to read and process the CSV file data containing Comma in its value. As per the syntax of the fgetcsv() function, it receives character inputs for specifying the field delimiter, field enclosure and more. As the default enclosure is the double quotes character, we need not specify those parameters while invoking fgetcsv(). Supply the CSV input having values with Comma to the CSV to HTML conversion script that we have seen in the above section. This will output the CSV data with Comma in the HTML format as shown below. Export database records to CSV in a generic wayWhile exporting a database, the backup file can be created in various formats SQL, CSV, Excel. In a previous tutorial, we have seen how to export a database to a CSV file. For doing this database backup programmatically, we need to execute appropriate MySQL statements to extract the structure and the data. By doing this, the backup will be ready with the database table’s create statements, insert queries dumped with data, statements for Indexes, auto increment and more. The PHP code for exporting database records to CSV is as follows.
In this code, the database structure and data are extracted and prepared in the form of CSV string. Then the prepared backup content can be downloaded to the browser by using PHP header() function with the specification if Content-Type. In the following sections, we will see how to download CSV by using Content-Type. How to export CSV using fputcsv?If you are only going to take the data backup instead of a complete database, then the fputcsv() function is enough. This function accepts the target CSV handle and the input array as it mandatory arguments. The input array must contain the row of column names or column values. The following PHP code shows how to exports MySQL records to a CSV file using fputcsv(). In this code, the database column names and values are extracted row by row and put it into the target CSV. The target CSV handle is created before executing the fputcsv() function.
Download as CSV File via browser using Content-TypeIn the above code, the PHP header() function is used to specify the Content-type, Content-disposition and more specifications. With these settings, the header will be sent to the browser with the CSV file attachment to be downloaded. By adding the header() function with Content-type: application/csv then CSV file will be downloaded to the browser. Read CSV using PHP built-in functionsPHP supports to read a CSV file by proving built-in functions. In this article, we have seen several examples to handle CSV with PHP functions like fgetcsv(), str_getcsv(). All these PHP functions are used in the above sections to read CSV file before processing it. The fgetcsv() function is used to read the CSV file data with the reference of the file handle. The str_getcsv() will accept the CSV string instead of the file pointer. Then the CSV string will be parsed to read the data. ConclusionAs the CSV(Comma-Separated Values) is one of the popularly used data handling formats and every programmer should be comfortable in handling CSV data. PHP provides the best support for handling CSV file and you should be aware of the functions available. Hope you have been introduced to all about CSV in PHP. If there is any topic missing, let me know it via the comments below and I will include that in the article. ↑ Back to Top What is a CSV file used for?A CSV is a comma-separated values file, which allows data to be saved in a tabular format. CSVs look like a garden-variety spreadsheet but with a . csv extension. CSV files can be used with most any spreadsheet program, such as Microsoft Excel or Google Spreadsheets.
What is a CSV file example?A CSV file is a list of data separated by commas. For instance, it may look like the following: Name,email,phone number,address. Example,[email protected],555-555-5555,Example Address. Example2,[email protected],555-555-5551,Example2 Address.
How do I process a CSV file in PHP?Open the PHP file and write the following code in it which is explained in the following steps.. Open dataset of CSV using fopen function. $open = fopen("filename. ... . Read a line using fgetcsv() function. ... . Use a loop to iterate in every row of data. ... . Close that file using PHP fclose() method.. What is in a CSV file?A CSV (comma-separated values) file is a text file in which information is separated by commas. CSV files are most commonly encountered in spreadsheets and databases. You can use a CSV file to move data between programs that aren't ordinarily able to exchange data.
|