Importing fixed-width text files to Mysql with PHP
I'm trying to import fixed with text files into a Mysql table. I'm digging around for answers, but my main issue is that I can't figure out the logic of how I should do this. Maybe someone could offer some hints on process:
Steps
1.fopen
the file
$file_handle = fopen("thefile.txt", "r");
2. Use feof
to go to the end of the file. Separate each line. (I have know idea why, but that $output line works.
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$lines = explode('|', $line_of_text);
$output = $lines[0] . $lines[1]. "<BR>";
All of this works fine. It reads the fixed-width file, and displays it all as it should - line by line. But how do I setup the columns before I import it to Mysql?
I thought maybe doing somethin开发者_开发问答g like this might do the trick to define the right columns:
echo substr($output,0,5);
echo substr($output,5,10);
echo substr($output,16,5);
But that doesn't work. Basically, can someone outline the steps I need to go through? I'm not asking for a solution, but at the moment, I don't even know what to Google for when I don't know what steps should come next.
Sorry for the complete beginner question here, but any help would be very much appreciated.
Thanks
Terry
[I'm not 100% sure how to import to Mysql either, but I wanted to get this much out of the way. IE: How do I setup the substrings to define my columns]
Fixed width files (with seperate portions of data) are best handled with fscanf
while($data=fscanf("%5s%10s%5s\n",$file_handle)){
var_dump($data);
}
However, explode
ing on '|' makes me think fgetcsv may work too, and if that works a LOAD DATA
command in MySQL could possibly skip PHP altogether.
精彩评论