Page 1 of 1

Text file to database

Posted: Sun Feb 02, 2003 10:33 am
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

Posted: Sun Feb 02, 2003 1:29 pm
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);
?>

Posted: Sun Feb 02, 2003 4:26 pm
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";

Posted: Sun Feb 02, 2003 5:04 pm
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.