Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to import data from excel file using PHP and then if possible, save it to a MySQL database.
Importing from Excel files (XLS) is way harder than improting from CSV files. Usually I save my XLS to CSV with Excel then work on this CSV with PHP...
Look at PHP function fgetcsv at:
http://ca.php.net/manual/en/function.fgetcsv.php
<?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);
}
?>
If you still want to load XLS directly from PHP it's possible (but how reliable)... A quick seach resulted in http://sourceforge.net/projects/phpexcelreader/ which might be helpful.
Quite possible. You can save your Excel file as a CSV file, and use fgetcsv() to read that file in to PHP. fgetcsv() will parse your data into an array, which you can then create SQL queries out of to put into your database.
If all you're doing is putting it into a database, you might be able to bypass the need for a PHP script entirely and just use MySQL's LOAD DATA INFILE syntax on your CSV file instead:
LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);
Best bet is to export from Excel to a CSV (Comma separated values) file. These files are easy to parse and load. If you are reading directly from an XLS file, I'm not sure how to do that. You might want to look and see if there is a libarary for PHP that can read Excel data files.
Here's a tutorial on reading/writing an Excel spreadsheet directly (without having to export to CSV). The necessary packages are available from SourceForge and PEAR (cf. article).
<?
i$db = mysql_connect(“localhost”, “root”, “”) or die(“Could not connect.”);
if(!$db)
die(“no db”);
if(!mysql_select_db(“test”,$db))
die(“No database selected.”);
if(isset($_POST['submit']))
{
$filename=$_POST['filename'];
$handle = fopen(“$filename”, “r”);
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE)
{
$import=”INSERT into sample(name,email) values(‘$data[0]‘,’$data[1]‘)”;
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print “Import done”;
}
else
{
print “<form action=’import.php’ method=’post’>”;
print “Type file name to import:<br>”;
print “<input type=’text’ name=’filename’ size=’20′><br>”;
print “<input type=’submit’ name=’submit’ value=’submit’></form>”;
}
?>
Source
Related
I have a CSV that is downloaded from the wholesaler everynight with updated prices.
What I need to do is edit the price column (2nd column) and multiply the current value by 1.3 (30%).
My code to read the provided CSV and take just the columns I need is below, however I can't seem to figure out how to edit the price column.
<?php
// open the csv file in write mode
$fp = fopen('var/import/tb_prices.csv', 'w');
// read csv file
if (($handle = fopen("var/import/Cbl_4036_2408.csv", "r")) !== FALSE) {
$targetColumns = array(1, 2, 3); // get data from the 1st, 4th and 15th column
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$targetData = array(); // array that hold target data
foreach($targetColumns as $column){ // loop throught the targeted columns array
if($column[2]){
$data[$column] = $data[0] * 1.3;
}
$targetData[] = $data[$column]; // get the data from the column
}
# Populate the multidimensional array.
$csvarray[$nn] = $targetData; // add target data to csvarray
// write csv file
fputcsv($fp, $targetData);
}
fclose($handle);
fclose($fp);
echo "CSV File Written Successfully!";
}
?>
Could somebody point me in the right direction please, explaining how you've worked out the function too so I can learn at the same time.
You are multiplying your price column always as - $data[0] * 1.3.
It may be wrong here.
Other views:
If you are doing it once in a lifetime of this data(csv) handling, try to solve it using mysql itself only. Create the table similar to the database, import the .csv data into that mysql table. And then, SQL operate as you want.
No loops; no coding, no file read/write, and precise control over what you want to do with UPDATE. You just need to be aware of the delimiters (line separators eg. \r\n, column separators (eg. comma or tab or semicolon) and data encoding in double/single-quotes or not)
Once you modify your data, you can export it back to csv again.
If you want to handle the .csv file itself, open it in one connection (read only mode), and write to another file - saving the original data.
you say that the column that contains the price is the second but then use that index with zero. anyway the whole thing can be easier
$handle = fopen("test.csv", "r");
if ( $handle !== FALSE) {
$out = "";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$data[1] = ((float)$data[1] * 1.3);
$out .= implode(";",$data) . "\n";
}
fclose($handle);
file_put_contents("test2.csv", $out);
}
this code open a csv file with comma as separator.
than read every line and for every line it's multiplies the second coloumn (index 1) for 1.3
this line
$out .= implode(";",$data) . "\n";
generate a line for new csb file. see implode on the officile documentation ...
after I close the connection to the file. and 'useless to have a connection with two files when you can do the writing of the second file in one fell swoop. the thing is true for small files
I am building a website in which i want to give the users a choice to upload their excel file which has all the data.
Website is built on PHP, Database used- MySQL.
When a user uploads the excel sheet, all the data has to be imported into my Database. Now i want to do it programatically using PHP. Can anyone help me out with this. The code should also be able to extract data from multiple tabs in the excel file.
Thank you.
You can try with any of the below libraries if you want Excel file itself need to be imported.
http://phpexcel.codeplex.com/
http://sourceforge.net/projects/phpexcelreader/
Note :
Importing from Excel files is harder than improting from CSV files. So I suggest you to provide an option for importing into MySQL from CSV. (Users can convert XLS to CSV using Excel)
Look at PHP function fgetcsv at:
http://ca.php.net/manual/en/function.fgetcsv.php
Eg.
<?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);
}
?>
First, try to avoid Excel format in favor of CSV. It is much faster and simpler.
Also, you can use PHPExcel library.
you should use PHPExcel
http://phpexcel.codeplex.com/
you can use following examples
http://phpexcel.codeplex.com/wikipage?title=Examples
you can also have a look at this link
https://code.google.com/p/php-excel-reader/wiki/Documentation
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to extract data from csv file in php
I have some data in XLS, I save them as CSV, the delimiter is **comma*.
Then I am trying to load the data from this CSV file:
$input = explode("\r\n", fread($file, filesize("my_data.csv")));
print_r($input);
The output:
Array ( [0] => data from the CSV file)
This is the problem - in the array is always just one item, where are printed out all data from the CSV file. How is that possible? Why isn't in the array as much items as is rows in the CSV file?
Also, I've tried to change "\r\n" for "\n", but it's the same.
What I am trying to do - load each line from the CSV file and this each line to process.
EXAMPLE OF THE FILE:
a,b,c,d
e,f,g,h
OUTPUT:
a,b,c,d e,f,g,h
I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row = implode (",",$data); //puts back together the row from the csv
echo $row. "\n"; //assuming you want a visual linebreak on console, add the \n
}
fclose($handle);
}
How I solved this issue:
In the XLS file, before exporting the file into CSV, I added in the end of sheet one more column with the char '.
I need to be able to output contacts via a loop on a page from a CSV file downloaded from Outlook.
If the user has the file on their local machine, I suppose I need some sort of upload mechanism, then let my script read uploaded file and then run the results via some loop and output one contact per line.
Each line will have a checkbox next to a contact and if checked, the form will post results and they will be written into db.
Normal format of Outlook .CSV example file here
I only need Name and email. First and last can be merged in just Name. I suppose i need to run some sort of email validation to reject malformed entries...
Just trying to understand what needs to be done.
You should look into fgetcsv, which can read your CSV file and return an array to you. This is really easy to work with.
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />";
}
}
fclose($handle);
}
For information about reading the csv file check out this http://php.net/manual/en/function.fgetcsv.php
I have a huge CSV file (10M records) in the following format.
147804,AC,34,15AUG09,09:00,15AUG09,21:00,YYZ,YVR,PLS
147816,AC,34,26AUG09,09:00,01SEP09,21:00,YYZ,YVR,PLS
I need to import them into a mysql database. How can I change all the months to numeric months and preferably into yyyy/mm/dd format.
Thanks
This is difficult to accomplish with regex and would be error prone. PHP has CSV support built-in and it’s a lot safer.
<?php
if (($if = fopen("src_file.csv", "r")) !== FALSE) {
if (($of = fopen("dst_file.csv", "w")) !== FALSE) {
while (($cols = fgetcsv($if)) !== FALSE) {
$cols[3] = date('Y/m/d',strtotime($cols[3]));
$cols[5] = date('Y/m/d',strtotime($cols[5]));
fputcsv($of, $cols);
}
fclose($of);
}
fclose($if);
}
?>
I don’t know if it would be more efficient to just store $cols in the database or create a new file and import it. I don’t have any benchmarks.
Amazingly, this seems to do the trick :
echo date('Y/m/d', strtotime('15AUG09'));
returns : 2009/08/15.
If you can manage to parse your CSV, you'll get your date in the format you want.