1

我在将数据从 .txt 文件传输到我的数据库时遇到问题。我有 10 个 .txt 文件,并且想将其所有数据传输到我的数据库。下面的代码是我迄今为止只为一个 .txt 文件尝试的。它给出的错误。当此人单击上传时,我将 zip 文件上传到文件夹中的服务器上传。执行此操作的代码如下:

if(isset($_FILES['zip'])){
    $errors = array();

    $zip = new ZipArchive();

    if(strtolower(end(explode('.', $_FILES['zip']['name'])))!=='zip'){
        $errors[] = 'That does not look like a .zip file.';
    }

    if($_FILES['zip']['size']>104857600){
        $errors[] = 'There is a size limit of 100MB';
    }

    if($zip->open($_FILES['zip']['tmp_name'])==false){
        $errors[]='Failed to open zip file.';
    }

    if(empty($errors)){
        $extracted_files = array();

        for($i=0;$i<$zip->numFiles;$i++){
            $entry_info = $zip->statIndex($i);

            $extracted_files[] = $entry_info['name'];
        }

        print_r($extracted_files);

        $zip->extractTo('./uploads');
        $zip->close();
    }
}

这会上传 zip 文件并解压缩它们。现在我想从 .txt 文件中读取数据并填充我的数据库。下面的代码是我所拥有的,但我得到了错误,特别是文件所在的路径。如果有人可以帮助我下面的代码,以及文件路径的帮助,或者建议我将文件放在另一个地方。代码如下:

$string = file_get_contents("set_1.txt","r");
$myFile = "/Applications/MAMP/bin/mamp/uploads";
$fh = fOpen($myFile,'w') or die("could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);

$sql = mysql_connect("localhost", "root","root");
if(!$sql){
    die("could not connect: " . mysql_error());
}

mysql_select_db("Tweet_Corpora");
$result = mysql_query("LOAD DATA INFILE '$myfile'" . " INTO TABLE Display FIELDS TERMINATED BY '/\s+/'");

if(!$result){
    die("could not load. " . mysql_error());
}

我的表如下所示:

|id |tweet_id |raw_tweet |normalized_tweet|

我只需要填写 tweet_id 和 raw_tweet 列

我的数据在每个文件中如下所示:

57587072533413889   @NAYDIVAA1 thought I saw u today u know
57743998223265792   The art of sleeping in the early morning and waking up at tea time.
57817604059959296   RT @dilleeeey: I'm very very very hungry. But I'm lazy to eat$

请帮忙。真的很感激。

4

1 回答 1

0
$string = file_get_contents("set_1.txt","r");
$myFile = "/Applications/MAMP/bin/mamp/uploads";
$fh = fOpen($myFile,'w') or die("could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);

在这一部分中,您将读取可能位于根路径中的文件的文件内容,因为您没有定义路径。

接下来,您在目录上运行 fopen 并向其写入内容。这不是它的工作原理。如果要向文件中写入内容,则应打开该文件。我什至不明白您为什么要尝试写入文件,而您已经获得了包含内容的文件。更奇怪的是,您在文件打开失败的那一刻显示 mysql_error() 。这两个人没有任何关系。你甚至没有连接数据库。

我不熟悉 LOAD DATA INFILE,但您的第一部分可能需要如下所示:

$string = file_get_contents("/path/to/file/set_1.txt","r");

$sql = mysql_connect("localhost", "root","root");
if(!$sql){
    die("could not connect: " . mysql_error());
}

mysql_select_db("Tweet_Corpora");
$result = mysql_query("LOAD DATA INFILE '$myfile'" . " INTO TABLE Display FIELDS TERMINATED BY '/\s+/'");

if(!$result){
    die("could not load. " . mysql_error());
}

如果你有大文件,你最好使用 fopen 并只读文件的一部分。也许这个问题也可以帮助你: Read a text file and transfer contents to mysql database

于 2013-08-04T15:48:05.813 回答