Text file to database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
leebo
Forum Commoner
Posts: 44
Joined: Sun Oct 20, 2002 9:49 am

Text file to database

Post by leebo »

HI

I`m trying to read data from a text file and then store it into the database so i can save the content of the text file daily, A kind of backup:

to read the file i`m using

$filename = "backup.txt";
$fp = fopen ($filename, "r" ) or die ("could not find file");
while ( ! feof( $fp ) ){
$line = fgets ($fp, 1024 );
print "$line<BR>";
}

this prints out the file but how do i convert this into a single string like

$data= nl2br($line);

so i can add it to the database

Thanks
User avatar
daven
Forum Contributor
Posts: 332
Joined: Tue Dec 17, 2002 1:29 pm
Location: Gaithersburg, MD
Contact:

Post by daven »

I tend to use tab/carriage return delimited text files and the SQL "LOAD DATA" call.

States DB table:

Code: Select all

Abr	VARCHAR(2)	NULL,
State	VARCHAR(30)	NULL
states.txt

Code: Select all

AK	AK-Alaska		
AL	AL-Alabama	
AR	AR-Arkansas	
AZ	AZ-Arizona	
CA	CA-California	
CO	CO-Colorado	
CT	CT-Conneticut	
DC	DC-District of Columbia	
DE	DE-Delaware	
FL	FL-Florida	
GA	GA-Georgia	
HI	HI-Hawaii

State_Data.php:

Code: Select all

<?php
$qry_state_data="LOAD DATA LOCAL INFILE "./states.txt" INTO TABLE States";
mysql_query($qry_state_data,$conn) or die($qry_state_data);
?>
User avatar
lazy_yogi
Forum Contributor
Posts: 243
Joined: Fri Jan 24, 2003 3:27 am

Post by lazy_yogi »

to convert to a single string use the .= operator to append to a string. Eg.

Code: Select all

$str = "this";
    $str .= " is crazy";
is the same as

Code: Select all

$str = "this is crazy"
So you'd use :

Code: Select all

$line = "";
while ( ! feof( $fp ) )&#123; 
    $line .= fgets ($fp, 1024 ); 
    $line .= \n";
&#125;
the you could use nl2br($line);

but you might as well change the newlines to breaks by instesd of using

Code: Select all

$line .= \n";
use

Code: Select all

$line .= <BR>\n";
User avatar
redcircle
Forum Commoner
Posts: 43
Joined: Fri Jan 31, 2003 8:47 pm
Location: michigan, usa

Post by redcircle »

Code: Select all

$filename = "backup.txt"; 
$fp = fopen ($filename, "r" ) or die ("could not find file"); 
$file = fread ($fp, filesize($filename) ); 
print "$file";
That puts the entire contents of the file into one string which can then be put in a database.
Post Reply