Re: formating text to insert in to database
| From: | Richard Lynch | Date: | Sat, 16 Dec 2000 22:25:22 +0000 |
| Subject: | Re: formating text to insert in to database | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-30686@lists.php.net to get a copy of this message | ||
> i have a large text file i need to format in a way that i can insert it
> into a database so its sorted properly.
>
> the text file looks something like this:
>
> string1 string2 string3 string4 string5
>
>
> how can i get these strings out so i can insert them in to the database?
Assuming the space (and/or newline) is your significant delimiter, you could
do this.
$path = '/full/path/to/text/file';
$file = fopen($path, 'r') or die("Could not open $path");
while (!feof($file)){
$line = fgets($file, 1024); #larger number may be good...
$strings = explode(' ', $line);
while (list(,$string) = each($strings)){
$string = addSlashes($string);
$query = "insert into string_table (string) values('$string')";
mysql_query($query) or die($query);
}
}
If sometimes there are multiple spaces, you will want to verify that $string
is non-empty.
If characters other than space are delimiters, you may want to look at
http://php.net/strtok rather than explode().
If performance is an issue, you might be able to create a single insert with
multiple rows (I forget how) and "batch" the queries to reduce the number of
queries... You'd have to experiment to see what is a good number of strings
to batch together without running into trouble with overly large strings
degrading PHP and/or overflowing the query buffer limit.