read write csv files in PHP


 Parsing CSV files in PHP

 

coding-zon-read-write-csv-php

 

 

What is CSV?

CSV means comma separated values. Each row of information is separated with one special character, usually it is comma(,) or semicolon(;), and contains an extension as '.csv'. Generally these files are opened in Excel sheets. 

Why CSV?

CSV file allows transmitting data from different sources. Let us say you can shift excel data to MySQL table or MySQL table to Oracle table and so on. CSV files supported by all the databases.

To deal with CSV files, there are two predefined functions available in PHP.

fputcsv() --> to write csv data to file
fgetcsv() --> read csv data from a file

In this article we will learn how to read data from a csv file, and write csv data to a file using the above functions in PHP.

1. Writing CSV Data to File

 

PHP fputcsv( ) Function :  To write csv data to a file.

Syntax:

fputcsv(filepointer, arrayoffields, separator) ;

In this article I will show you 2 ways, to write CSV data to a file.

1. PHP array. 

2. MySQL table.

GoTop


1. Writing Array to CSV

 
 

array-to-csv.php

 
Example-1: 
 
<?php
 
 
$user[0] = array('1','John','Canada','john@test.com');  
$user[1] = array('2','Steave','London','steave@example.com');
$user[2] = array('3','Brown','Sidney','brown@mysite.com');

 

$file = fopen("contacts.csv","w"); 
 
// iterates in every line of user array
 
 foreach ($user as $line) {
  fputcsv($file, $line);
}

fclose($file);
 
echo "file created";

 ?>
 
 Result: contacts.csv file created in current folder
 
 
 
 
 
 
 Db Queries
--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(25) NOT NULL,
  `password` varchar(25) NOT NULL,
  `email` varchar(25) NOT NULL,
  `mobile` varchar(12) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`user_id`, `username`, `password`, `email`, `mobile`) VALUES
(1, 'admin', 'admin123', 'admin@testmail.com', '3456432253'),
(2, 'user1', 'user432', 'user@testmail.com', '54323456'),
(4, 'user3', 'user3', 'user3@example.com', '8092809322'),
(5, 'admin2', 'admin2', 'admin2@example.com', '2342342423'),
(6, 'user4', 'user4', 'user3@example.com', '995820320'),
(8, 'user5', 'user5', 'user5@example.com', '995820320'),
(9, 'admin3', 'admin3', 'admin3@example.com', '09912338398'),
(10, 'admin4', 'admin4', ''admin4@example.com', '09912238398'); 
 
 

 

 MoveTop

 
 

 2. Writing MySQL to CSV

 
 

mysql-to-csv.php

 
<?php 
 
$host = "localhost";
$user = "root";
$password = "";
$database = "usersdb";
 
$con = mysqli_connect($host,$user,$password,$database);
	
	$query="select * from users" ;
	
	$result =mysqli_query($con,$query);
	
	$file = fopen("contacts2.csv","w");

	
	while($row = mysqli_fetch_assoc($result))
	{
	
          fputcsv($file, $row);
         
        }

fclose($file);
 
	 
	 
?>

 MoveUp

 

Reading CSV in PHP

 

 

 

2. Reading CSV Data from File

 

PHP fgetscsv() Function  :  Reads line of data as an array from CSV file.


 

 

Take a new Notepad file, copy the below data and save it as data.csv.
Next create a PHP file in the same folder copy the below given code and run it.

 

data.csv 

 
1,John, Canada, john@gmail.com
2,Steve, London, steave@ymail.com
3,Brown, Sidney, brown@hotmail.com 
 
 
Then It looks as shown in the picture
 
 
e-trainings-csv-file

 
 

 read-csv.php

 
<?php
 
$file = fopen("data.csv", "r");
 
while (!feof($file) ) {
 
$line = fgetcsv($file, 1024);
 
print $line[0].$line[1].$line[2].$line[3]."<br>"
 
 
fclose($file);
 
?>

 Result:

1John Canada Canada
2Steave LondonLondon
3Brown Sidney Sidney

 

 MoveToMenu

 

Reading CSV to associative array in PHP

 read-csv2array.php

<?php 
 
$assoc_array = [];
if (($file= fopen("data.csv", "r")) !== false) {                 // open for reading 
    if (($data = fgetcsv($file, ",")) !== false) {        
        $keys = $data;                                             
    }
    while (($data = fgetcsv($file,",")) !== false) {      // loop remaining rows of data
        $assoc_array[] = array_combine($keys, $data);              // push associative subarrays
    }
    fclose($file);                                               // close when done
}
echo "<pre>";
   	print_r($assoc_array);                                      // print result
echo "</pre>";
?>

 

 

 MovetoTop

 

 

Comments

Popular posts from this blog

Recently viewed list in PHP Mysql

Import CSV File Into MySQL Using PHP

Shoppingcart using PHP Sessions - Miniproject