逐行读取文件并在数据库行中保存一行

时间:2013-04-09 10:38:33

标签: php

我无法理解如何在数据库中保存一行... 我有来自网络的文件,我带他用CURL。那个文件看起来像这样:

www.example.com/file.txt

  

REFALIAS http:// .example.com / data / / * http://example.com/data/?q= $ 2

     

REFALIAS http:// .example.com / data / / * http://example.com/data/?q= $ 2

     

REFALIAS http:// .example.com / data / / * http://example.com/data/?q= $ 2

     

REFALIAS http:// .example.com / data / / * http://example.com/data/?q= $ 2

所有来自网络的我使用CURL并保存在我的web根目录中的新文件中... 现在我对在数据库中保存行感到困惑。

我的DB shema看起来像这样:

ID  |   TYPE        |   LINK_ONE                      |  LINK_TWO
--------------------------------------------------------------------------------------
 1  |  REFALIAS     |  http://*.example.com/data/*/*  | http://example.com/data/?q=$2
 2  |  REFALIAS     |  http://*.example.com/data/*/*  | http://example.com/data/?q=$2
 3  |  REFALIAS     |  http://*.example.com/data/*/*  | http://example.com/data/?q=$2

我试试这个:

<?php     
$fp = @fopen('myFile.txt', 'r');
    while(!feof($fp)) {
       $buffer = fwrite($fp, 999);
       list($type, $link_one, $link_two) = explode("\n", $buffer);
       mysql_query('INSERT INTO table ('type', 'link_one','link_two' VALUES("{$type}, {$link_one}, {$link_two}");
    }
?>

此返回注意:未定义的偏移量:2; 我尝试了很多像这样的例子,我不能保存db中的所有行。 我必须逐行采取并保存。 我只是爆炸成功,但如何分开所有......

的任何示例

1 个答案:

答案 0 :(得分:0)

试试这段代码:

<?php     
$fp = @fopen('myFile.txt', 'r');
    while(!feof($fp)) {
       $buffer = fgets($fp);
       if (empty($buffer)) continue;
       list($type, $link_one, $link_two) = explode(" ", $buffer);
       mysql_query('INSERT INTO table (`type`, `link_one`, `link_two`) VALUES(\'' . $type . '\', \'' . $link_one . '\', \'' . $link_two . '\')');
    }
?>
相关问题