Create CSV File In PHP
Last Updated : Jan 1, 2023
IN - PHP
In this tutorial we will show you the solution of create csv file in PHP, as we know CSV file is a type of spreadsheet and today we are going to create a spreadsheet with help of PHP.
First, there are many ways with help of which we can create CSV files.
Let us understand some ways with help of the example given below.
Step By Step Guide On Create CSV File In PHP :-
We can also create a CSV file with help of static content and with help of dynamic content.
Today, we are going to create a CSV file using the Dynamic method.
With help of this example, we are also able to create CSV files using static content. So, let us understand this way with help of the codes given below.
<?php $data = array( $_POST['name'], $_POST['password'], ); $result = fopen('data.csv', 'a'); fputcsv($result, $data); fclose($result); ?> <!DOCTYPE html> <html> <head> <title> create CSV file in PHP</title> </head> <body> <h1> TalkersCode </h1> <h2> Create CSV file in PHP </h2> <form action = "gfg.php" method = "post"> <label> Username </label> <input type = "text" name = "name" /> <br> <label> Password <label> <input type = "text" name = "password" /> <br> <input type = "submit" name = "submit" value = "Submit"> </form> </body> </html>
- As, here we see that we that in above example we show you an example in which HTML and PHP codes are used.
- Here, first of all, we create a basic structure of HTML, in which we use <!DOCTYPE html> which defines the type of document. And next one is our HTML tags. These tags are paired tags and all the data regarding HTML is written inside these tags.
- After we use our head tag which is again paired tag and contains the title and meta information of the webpage. The data written inside the head is not shown on the webpage.
- Now, next is the body which is the main tag of HTML. The data which we have written inside the body is shown on the webpage. Mostly all tags which are helpful to show data or information on the screen are written under the body tag.
- Now, as we see inside the body we write our PHP codes. These codes are started with <?PHP and end with ?>, these tags are known as basic PHP tags. Our PHP codes are always written under these interfaces. In our above example as we see inside this basic structure of PHP.
- As, above we create a form with help of PHP and HTML. Whereas in PHP codes, we get the values of the form and form an array. The array will be stored in a variable. At next, we open the file in append mode using fopen().
- Then, we insert form data into our CSV file and at last, we close the file. The above example will be understood in a better way when we use these codes practically.
At last, in conclusion, here we can say that with the help of this article we can understand how to create a CSV file in PHP.
I hope this tutorial on create csv file in PHP helps you and the steps and method mentioned above are easy to follow and implement.