使用PHP将固定宽度的文本文件导入Mysql [英] Importing fixed-width text files to Mysql with PHP
问题描述
我正在尝试将带有文本文件的修复导入到Mysql表中。我正在寻找答案,但我的主要问题是我无法弄清楚我应该如何做到这一点的逻辑。也许有人可以提供一些流程提示:
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:
步骤
1. fopen
文件
$file_handle = fopen("thefile.txt", "r");
2。使用 feof
转到文件末尾。分开每一行。 (我知道为什么,但是$输出行有效。
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>";
所有这一切都正常。它读取固定宽度文件,并显示它一切都应该 - 逐行。但是我如何在将它导入Mysql之前设置列?
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 something 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.
谢谢
特里
[我不是100%肯定如何导入到Mysql,但我想要这么做。 IE:如何设置子串以定义我的列]
推荐答案
固定宽度文件(具有单独的部分数据)最好用 fscanf 处理
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);
}
然而,爆炸
'|'让我觉得 fgetcsv 也可能有效,如果有效命令可能会完全跳过PHP。
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.
这篇关于使用PHP将固定宽度的文本文件导入Mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!