Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import csv file in PHP?

Tags:

php

csv

I am very new to web development. In fact, I am just starting to learn.

Can somebody please give a complete but very simple example on how to import CSV file in PHP? I tried the one I got from the internet but I'm very confused because it's complicated for me. I am using the WAMP server with PHP 5.3.5, Apache 2.2.17, and MySQL 5.5.8. Please help.

I tried to paste the code but it's messy. Honestly, I am also very new to StackOverflow.

like image 684
Newbie Coder Avatar asked Apr 28 '11 03:04

Newbie Coder


People also ask

How do I Import a CSV file?

On the File menu, click Import. In the Import dialog box, click the option for the type of file that you want to import, and then click Import. In the Choose a File dialog box, locate and click the CSV, HTML, or text file that you want to use as an external data range, and then click Get Data.

How you can Import a file in PHP?

PHP Include Files. The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.


2 Answers

From the PHP manual:

<?php $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) {     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {         $num = count($data);         echo "<p> $num fields in line $row: <br /></p>\n";         $row++;         for ($c=0; $c < $num; $c++) {             echo $data[$c] . "<br />\n";         }     }     fclose($handle); } ?> 
like image 103
coreyward Avatar answered Oct 02 '22 11:10

coreyward


I know that this has been asked more than three years ago. But the answer accepted is not extremely useful.

The following code is more useful.

<?php $File = 'loginevents.csv';  $arrResult  = array(); $handle     = fopen($File, "r"); if(empty($handle) === false) {     while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){         $arrResult[] = $data;     }     fclose($handle); } print_r($arrResult); ?> 
like image 32
Alex Avatar answered Oct 02 '22 12:10

Alex