Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts

How to Create and Download CSV File in PHP

On 6/08/2018 Be the first to comment!

Hi! Here we will see how to create a csv file and download it using php. CSV is one of the popular data storage methods used on the Web. Being a modern language, PHP has no problems handling various data formats including csv. It offers native functions to read and write csv files. With fputcsv() method, you can write data as a csv file and force it to download.

Clicking on a file url (link) will just open it in the browser window without downloading. The exe and zip formats are an exception here. But in case you need to download it directly to client's hard disk, then you have to make use of the readfile() function.

Let's see how to do it.

php create download csv file

PHP - Create CSV File:

The following snippet creates a csv file named 'myfile.csv' on your current working directory.

<?php
// data array
$user = array(1, 'Johnson', 'johnson@mydomain.com', 'Miami');
// filename
$filename = 'myfile.csv';

// write to csv file
$fp = fopen($filename, 'w');
fputcsv($fp, $user);
fclose($fp);
?>

Okay! We have created the csv file. Next we'll move on to the download part.

Download CSV File:

As I said before, you must use readfile() along with the proper header to force download of the file. Here's the code to do it,

<?php
// download file
header('Content-type: text/csv');
header('Content-disposition:attachment; filename="'.$filename.'"');
readfile($filename);
?>

Sending the header along with the download option will force open the 'Save File' dialog in the user's browser window.

We have used two header() functions in the above script.

The first one sets the MIME type of the content sent. Since it is 'text/csv' for csv data, we need to set it as the 'Content-type'.

The second line provides the filename to be used for storing and force the browser to display the save dialog.

Read Also:

That explains how to create csv file and automatically download it in php. I hope you find this post useful. Please share it on social media if you like it.

How to Import CSV File into MySQL with LOAD DATA INFILE

On 4/18/2018 Be the first to comment!

I tried to import a csv file into mysql with php script. It is a simple solution if you have a small set of data to import. But if you have hundreds of thousands of records, don't even think about it. You need something different to read through a large dataset quickly. MySQL's LOAD DATA INFILE command works like a charm and can be executed from the command line.

Using LOAD DATA INFILE allows you to load csv or any other delimited data file to the mysql table with a single command. It comes with several options and we will see below what they are and how to use them to import the csv data set into the mysql table.

Using LOAD DATA INFILE Command:

The LOAD DATA INFILE command in mysql loads data from a file into the table at high speed. The file path specified must be absolute or relative.

1. Importing CSV File into MySQL:

Let's say we have a mysql table 'customers' with the following structure.

MySQL Table: Customers
CREATE TABLE `customers`(
    `id` INT(8) NOT NULL ,
    `name` VARCHAR(30) NOT NULL ,
    `email` VARCHAR(40) NOT NULL ,
    `location` VARCHAR(25) NOT NULL ,
    PRIMARY KEY (`id`)
);

And a csv file customers.csv with data that we want to insert into the 'customers' table.

CSV File: Customers.csv
csv file to import into mysql

Now to import the csv data into the table, use the following sql statement.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABL    E customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Executing the above sql will import records to the given 'customers' table.

customers mysql table after running load data infile command

Our csv file has a column header as the first row, so we used the option IGNORE 1 LINES which will skip the first row. If you don't have the column header, don't use it.

Also make sure the file path is correct. You can use the format 'c:/tmp/customers.csv' or 'c:\\tmp\\customers.csv'.

This method will only work when your mysql table has the same sequence of columns as of the csv file.

2. Importing File with Different Column Sequence from Table:

Consider the scenario where your table and csv file column sequence are different. In this case, you must explicitly specify the order of the column name to ensure that the data is imported correctly.

LOAD DATA INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

3. Importing Data to Remote MySQL Database Server:

If you have your file on the local machine and not on the server, use the word LOCAL. This will import file from the client (local system) to a remote mysql database server.

LOAD DATA LOCAL INFILE 'c:/tmp/customers.csv'
INTO TABLE tbl_customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(id,name,email,location);

When you include the LOCAL option, the file is expected to be located on the client and not on the server.

You can also use the mysqlimport utility to load csv data into the database. It's very similar to LOAD DATA INFILE, except that mysqlimport supports multiple file loading and the latter does not.

Read Also:

If you have a large dataset to import, go for the LOAD DATA INFILE command, as it is extremely faster than doing it with any other script. I hope this tutorial is useful to you. Please share it on social media if you like it.

Convert JSON to CSV using PHP (JSON Keys as Column Headers)

On 11/08/2017 1 Comment so far

Hi! Here's how to convert json to csv in php by using json keys as column headers for csv file. Even though json format is immensely popular for data exchange over web, there are times you may need to work with csv data and have to convert json to csv. Being a modern language, php doesn't have trouble handling both data formats but unfortunately there's no one step solution to convert json to csv using php. But don't worry! I have created a simple php script for json to csv conversion.

In case you don't know, json stores data as 'key:value' pairs. And the function I have created will take valid json keys and use it as column headers for the csv file during conversion.

I have already discussed about converting csv to json in php and below we'll see about converting json to csv in php.

But keep in mind there are so many things can go wrong during this conversion so you need to do proper error handling in the script.

How to Convert JSON to CSV in PHP?

We'll need a sample json file for converting to csv. So let's take this below one as example.

data.json

[
    {
        "Id": "1",
        "Name": "Suki Burks",
        "Position": "Developer",
        "Salary": "$114500"
    },
    {
        "Id": "2",
        "Name": "Fred Zupers",
        "Position": "Technical Author",
        "Salary": "$145000"
    },
    {
        "Id": "3",
        "Name": "Gavin Cortez",
        "Position": "Team Leader",
        "Salary": "$235500"
    }
]

PHP Function to Convert JSON to CSV:

Here's the php conversion function. The function has two parameters 1. $jfilename - which is the path of the json file to be converted and 2. $cfilename - and this is the csv filename where the converted data will be stored.

The script reads the json file contents, decodes json string into an array, remove the keys from the array and write it as column headers and parse through the array one by one and write down the data into csv file.

<?php
function jsonToCSV($jfilename, $cfilename)
{
    if (($json = file_get_contents($jfilename)) == false)
        die('Error reading json file...');
    $data = json_decode($json, true);
    $fp = fopen($cfilename, 'w');
    $header = false;
    foreach ($data as $row)
    {
        if (empty($header))
        {
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
        }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
    return;
}
?>
  • The function file_get_contents($jfilename) returns the content of the json file.
  • Next json_decode($json, true) decodes the json string into an associative array.
  • The function array_keys($row) will return the keys from an associative array.
  • And array_merge($header, $row) will keep the order of elements according to csv column headers.

Function Usage:

To convert json to csv file,

$json_filename = 'data.json';
$csv_filename = 'data.csv';
jsonToCSV($json_filename, $csv_filename);
echo 'Successfully converted json to csv file. <a href="' . $csv_filename . '" target="_blank">Click here to open it.</a>';

If everything goes right, this will convert the given json file into csv and display the csv file link like this on browser,

php json to csv conversion

Clicking on the link will open the csv file in Microsoft Excel.

Here's the complete script for your reference.

<?php
function jsonToCSV($jfilename, $cfilename)
{
    if (($json = file_get_contents($jfilename)) == false)
        die('Error reading json file...');
    $data = json_decode($json, true);
    $fp = fopen($cfilename, 'w');
    $header = false;
    foreach ($data as $row)
    {
        if (empty($header))
        {
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
        }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
    return;
}

$json_filename = 'data.json';
$csv_filename = 'data.csv';

jsonToCSV($json_filename, $csv_filename);
echo 'Successfully converted json to csv file. <a href="' . $csv_filename . '" target="_blank">Click here to open it.</a>';
?>

Related Read: How to Convert CSV to JSON using PHP

That explains about converting csv to json in php. I hope you find this php script useful. Meet you in another interesting tutorial.

Convert CSV To JSON Using PHP (With Header Row As Keys)

On 11/08/2017 4 Comments so far

Hi! Here is the php script to convert csv to json with header row as keys. Both csv and json are used to store data but json is little more verbose and human readable and has become popular data exchange format among modern web services. Converting csv data into json format is little tricky especially if you want your json to be properly formatted as key:value pairs. The csv header row should be used as keys and the subsequent rows as values to form json string.

Unfortunately there is no direct way to do this but likely there is a workaround to bring out the desired result. The method used here is by far the most effective solution to convert csv to json with header row as keys.

Converting CSV to JSON using PHP

Let's take a sample csv file with header and some rows and convert it to json using php script.

Data.csv

Id,Name,Position,Salary
1,Suki Burks,Developer,$114500
2,Fred Zupers,Technical Author,$145000
3,Gavin Cortez,Team Leader,$235500

PHP Function to Convert CSV to JSON

This is the php function to convert csv to json representation. The function takes up a csv file as parameter, stores the headers as a separate key array and read the subsequent rows one by one into an array and finally combine both key and data array to form a proper key-value pair representation.

<?php
// php function to convert csv to json format
function csvToJson($fname) {
    // open csv file
    if (!($fp = fopen($fname, 'r'))) {
        die("Can't open file...");
    }
    
    //read csv headers
    $key = fgetcsv($fp,"1024",",");
    
    // parse csv rows into array
    $json = array();
        while ($row = fgetcsv($fp,"1024",",")) {
        $json[] = array_combine($key, $row);
    }
    
    // release file handle
    fclose($fp);
    
    // encode array to json
    return json_encode($json);
}
?>
  • The function fgetcsv($fp,"1024",",") reads a row from the csv file into an array. The second parameter "1024" is the maximum character length of the csv row and the third parameter "," represents the column delimiter.
  • The function json_encode() encodes the php array into json string.

Function Usage

Call the above php function like this to convert csv to json.

<?php
print_r(csvToJson("data.csv"));

// output

// [{"Id":"1","Name":"Suki Burks","Position":"Developer","Salary":"$114500"},{"Id":"2","Name":"Fred Zupers","Position":"Technical Author","Salary":"$145000"},{"Id":"3","Name":"Gavin Cortez","Position":"Team Leader","Salary":"$235500"}]
?>

If you want json to be stored in a separate file, then open a file and write to it. Check this tutorial to know how to write to a json file.

Thus with this small php utility function you can very easily convert csv to json string.

Also Read: How to Import CSV to MySQL Database in PHP

Import CSV File into MySQL Database using PHP Script

On 11/08/2017 11 Comments so far

Hi, this time I have come up with another useful php script, which will show you How to Import CSV File Data into MySQL Database using PHP. CSV Files commonly known as comma separated values is one of the most preferred data storage methods. And as a developer often you might find you in situation to import those huge csv data into database system. Though sounding simple, it's a nightmare in disguise. Here's where php comes to the rescue. With few lines of code, you can insert several hundreds of records in flash.

PHP supports several data formats like csv, json etc. and provides dedicated functions to handle such data formats. Hence without any third party solutions, we can to parse and store csv records in database using core php alone.

php script import csv into mysql database
Read Also

Create Sample MySQL Database

As an example, let's use our previous 'library' database for this tutorial. Just create a new database with name 'library' in mysql. Next you should create a table 'books' to store the details of the books in the library. For that run the below sql command.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `library`
--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `author` varchar(30) NOT NULL,
  `isbn` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Sample CSV File

Below is the sample csv file containing the books data and we'll import this csv file to the 'books' table.

books.csv
Learning PHP MySQL & JavaScript,Robin Nixon,ISBN-13: 978-1491918661
PHP and MySQL for Dynamic Web Sites,Larry Ullman,ISBN-13: 978-0321784070
PHP Cookbook,David Sklar,ISBN-13: 978-1449363758
Programming PHP,Kevin Tatroe,ISBN-13: 978-1449392772
Modern PHP New Features and Good Practices,Josh Lockhart,ISBN-13: 978-1491905012

Now it's time to move on to the php script part.

PHP Script to Import CSV File Data into MySQL Database

The CSV import process goes like this. With PHP open the '.csv' file, parse through it one line at a time and insert into mysql db. Following is the step by step procedure for doing so.

Step-1: Set the Database Connection Variables

First let's set the database connection variables and the right csv file path to import.

<?php
//set the connection variables
$hostname = "localhost";
$username = "username";
$password = "password";
$database = "library";
$filename = "books.csv";
?>

Step-2: Establish the MySQL Database Connection

Next we open the connection to mysql database using mysqli library.

<?php
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));
?>

Step-3: Open and Parse the CSV File

Now we should open the csv file in 'reading' mode and parse the record one at a time and insert into mysql table 'books'.

<?php
// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
    //insert csv data into mysql table
    $sql = "INSERT INTO tbl_books (name, author, isbn) VALUES('" . implode("','",$row) . "')";
    if(!mysqli_query($connection, $sql))
    {
        die('Error : ' . mysqli_error());
    }
}

fclose($fp);
?>

The line $fp = fopen($filename,"r"); will open the 'books.csv' file for reading and return the file handler to the $fp variable.

Next we loop through the entire file one record at a time. Using the line $row = fgetcsv($fp,"500",",") will fetch the complete row of the csv file one at a time, and "500" specifies the maximum length of the rows in the csv file and "," specifies the delimiter.

Finally we implode the fetched row and save it into mysql database using the INSERT query.

The line fclose($fp); closes the file handler after completely parsing through the entire file.

Step-4: Close the MySQL Database Connection

After inserting all the csv records into mysql, we finally close the database connection we established first.

<?php
//close the db connection
mysqli_close($connection);
?>

Here is the Complete PHP Script to Import CSV File into MySQL Database.

<?php
//set the connection variables
$hostname = "localhost";
$username = "username";
$password = "password";
$database = "library";
$filename = "books.csv";

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
    //insert csv data into mysql table
    $sql = "INSERT INTO tbl_books (name, author, isbn) VALUES('" . implode("','",$row) . "')";
    if(!mysqli_query($connection, $sql))
    {
        die('Error : ' . mysqli_error());
    }
}

fclose($fp);

//close the db connection
mysqli_close($connection);
?>

Now go back to mysql and check the library database after running the php snippet. You will find the csv file records inserted into the 'books' table.

And that was all about importing csv file into mysql database using php. There's also the reverse process of exporting mysql database to csv file with php. You can check it out.

Contact Form

Name

Email *

Message *