egoselfaxis
asked on
Importing data from a tab-delimited TXT file using PHP
I'm writing a PHP-based app that requires that data be imported into a MySQL datbase from a tab delimited TXT file.
The import file will initially be in XLS format, .. but will then be exported to tab-delimited TXT format using Excel's "Save As" functionality.
One of the problems that I know I'm going to run in to is that some of the data in the TXT file will contain quotation marks as qualifiers (ie: typically wrapped around individual column values that contains commas in them, ... such as item descriptions and dollar values, etc.).
I really don't want to have to involve any kind of "custom excel macro" or anything of the sort if I can help it, .. since that's always proven to be an annoyance.
So .. here is what I'd like to accomplish. I need a PHP-based script (preferably something procedural) that has these features:
1) Reads the contents of a tab-delimited TXT file (which already resides on the server) which contains 11 specifically named columns in it -- (ie: ItemName, ItemDescription, ReservePrice ...)
2) Checks to see if a piece of column data has quotation mark qualifiers surrounding it, .. and if so, .. it removes them from the data.
3) Checks to see if a piece of column data starts with a "$" symbol, .. and if so .. remove the "$" symbol, and also remove any commas that might exist ($2,400.00 --> 2400.00)
4) Insert the column data into the database -- 1 row at a time -- using the "sanitized" data.
Thanks!
- Yvan
The import file will initially be in XLS format, .. but will then be exported to tab-delimited TXT format using Excel's "Save As" functionality.
One of the problems that I know I'm going to run in to is that some of the data in the TXT file will contain quotation marks as qualifiers (ie: typically wrapped around individual column values that contains commas in them, ... such as item descriptions and dollar values, etc.).
I really don't want to have to involve any kind of "custom excel macro" or anything of the sort if I can help it, .. since that's always proven to be an annoyance.
So .. here is what I'd like to accomplish. I need a PHP-based script (preferably something procedural) that has these features:
1) Reads the contents of a tab-delimited TXT file (which already resides on the server) which contains 11 specifically named columns in it -- (ie: ItemName, ItemDescription, ReservePrice ...)
2) Checks to see if a piece of column data has quotation mark qualifiers surrounding it, .. and if so, .. it removes them from the data.
3) Checks to see if a piece of column data starts with a "$" symbol, .. and if so .. remove the "$" symbol, and also remove any commas that might exist ($2,400.00 --> 2400.00)
4) Insert the column data into the database -- 1 row at a time -- using the "sanitized" data.
Thanks!
- Yvan
This might be easier than you think. mySQL has a special command which can be used for importing csv files, called LOAD DATA INFILE.
http://dev.mysql.com/doc/refman/5.0/en/load-data.html
The statement you need is something like:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY '\t' ENCLOSED BY '"'
LINES TERMINATED BY '\n';
If you do this from PHP, you must double the backslashes and escape the double quote character:
$sql = "LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"'
LINES TERMINATED BY '\\n';";
Regarding the dollar values ($2,400.00 --> 2400.00), this should be removed by excel, check if it is in the csv file after export from excel. If they are there, you can remove them from the mysql table after import:
update tbl_name set dollarcol=replace(dollarco l,'$','');
update tbl_name set dollarcol=replace(dollarco l,',','');
http://dev.mysql.com/doc/refman/5.0/en/load-data.html
The statement you need is something like:
LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY '\t' ENCLOSED BY '"'
LINES TERMINATED BY '\n';
If you do this from PHP, you must double the backslashes and escape the double quote character:
$sql = "LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"'
LINES TERMINATED BY '\\n';";
Regarding the dollar values ($2,400.00 --> 2400.00), this should be removed by excel, check if it is in the csv file after export from excel. If they are there, you can remove them from the mysql table after import:
update tbl_name set dollarcol=replace(dollarco
update tbl_name set dollarcol=replace(dollarco
Right... it seems bportlock and me are would do this pretty much the same way! :)
ASKER
Well, although I appreciate the excellent suggestion, .. since I've already invested a lot of time in developing a PHP-based front end, it's important that my solution be an extension of the application I've already developed (My clients will need to be able to manage the import process by themselves, and will not be using any kind of MySQL client.).
Can this LOAD DATA INIFILE statement be executed using PHP? If so, how?
- Yvan
Can this LOAD DATA INIFILE statement be executed using PHP? If so, how?
- Yvan
>> Can this LOAD DATA INIFILE statement be executed using PHP? If so, how?
Yes, it can.
Yes, it can.
$sql = "LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"'
LINES TERMINATED BY '\\n';";
mysql_query($sql) or die(mysql_error());
ASKER
Unfortunately, .. I'm not going to be able to use this in this particular instance, as I can not dictate to the client what columns they need to include in their import file, ... or the specific order. Rather, they have given me an import file, and asked me to develop an import module based on that.
I've made some progress on my PHP import script since I posted my initial question (see attached code). However, I'm having a problem with not being able to figure out how to properly handle the end of a row (ie: new line). How do I adapt my script to handle the new lines? I suspect that my use of the explode function might not be adequate in this situation, .. and that my foreach loop might actually need to be nested inside another loop of some sort. Please advise.
Thanks!
- Yvan
I've made some progress on my PHP import script since I posted my initial question (see attached code). However, I'm having a problem with not being able to figure out how to properly handle the end of a row (ie: new line). How do I adapt my script to handle the new lines? I suspect that my use of the explode function might not be adequate in this situation, .. and that my foreach loop might actually need to be nested inside another loop of some sort. Please advise.
Thanks!
- Yvan
$importfile = $datadir . $_POST['importfile'];
$fd = fopen($importfile, 'r');
$theData = fread($fd, filesize($importfile));
fclose ($fd);
$delimiter = "\t";
$splitcontents = explode($delimiter, $theData);
$counter = "";
foreach ( $splitcontents as $data ) {
$counter++;
echo "<strong>Column #" . $counter . ": </strong> " . $data . "<br/><br/>";
if ($counter == '11') {
echo "<h3>New Row</h3>";
$counter = "";
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@cxr - just compared our solutions. Almost a copyright violation there.....
;-)
Cheers
brian
;-)
Cheers
brian
Yes, I wonder if there was some telepathic forces involved... ;)
>> How do I adapt my script to handle the new lines?
I agree with bportlock (surprise!), you should use fgetcsv() to read the file. However, to answer your question regarding your latest snippet, you could use the file() function to read the file into an array:
$data = file($importfile);
foreach($data as $line) {
$columns = explode("\t",$line);
}
http://php.net/manual/en/function.file.php
You could also read it into a string (like you allready do) and explode on "\n" first to get lines, loop over the lines and explode on "\t" to get the fields.
Beware that both of these solutions fails if any column contains a \t (tab) character. This is why fgetcsv() is a better solution, this function reads csv files correctly, even if the columns contains the separator.
I agree with bportlock (surprise!), you should use fgetcsv() to read the file. However, to answer your question regarding your latest snippet, you could use the file() function to read the file into an array:
$data = file($importfile);
foreach($data as $line) {
$columns = explode("\t",$line);
}
http://php.net/manual/en/function.file.php
You could also read it into a string (like you allready do) and explode on "\n" first to get lines, loop over the lines and explode on "\t" to get the fields.
Beware that both of these solutions fails if any column contains a \t (tab) character. This is why fgetcsv() is a better solution, this function reads csv files correctly, even if the columns contains the separator.
ASKER
bportlock -- the fgetcsv() has made things sooo much easier for me. Thanks so much!
- Yvan
- Yvan
LOAD DATA INFILE 'filename' INTO TABLE tableName
FIELDS TERMINATED BY '\t'
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
More at http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Then run a query to update the column(s) with $ and , in it
UPDATE tableName set moneyField = REPLACE( moneyField, '$', '' );
UPDATE tableName set moneyField = REPLACE( moneyField, ',', '' );
More at http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_replace
Once this data is sanitised you can copy it to the target table with an INSERT/SELECT
INSERT INTO targetTable
SELECT * FROM tableName
See http://dev.mysql.com/doc/refman/5.1/en/insert-select.html