如何从文本文件导入特定数据到mysql?

如何从文本文件导入特定数据到mysql?

问题描述:

我从DBpedia中下载的文件,与内容是这样的:如何从文本文件导入特定数据到mysql?

<http://dbpedia.org/resource/Selective_Draft_Law_Cases> <http://dbpedia.org/ontology/wikiPageExternalLink>  <http://supreme.justia.com/cases/federal/us/245/366/> . 
<http://dbpedia.org/resource/List_of_songs_recorded_by_Shakira> <http://dbpedia.org/ontology/wikiPageExternalLink> <http://www.shakira.com/> . 
<http://dbpedia.org/resource/Bucharest_Symphony_Orchestra> <http://dbpedia.org/ontology/wikiPageExternalLink> <http://www.symphorchestra.ro/> . 
<http://dbpedia.org/resource/Bucharest_Symphony_Orchestra> <http://dbpedia.org/ontology/wikiPageExternalLink> <http://symphorchestra.ro> . 
<http://dbpedia.org/resource/Bucharest_Symphony_Orchestra> <http://dbpedia.org/ontology/wikiPageExternalLink> <http://www.youtube.com/symphorchestra> . 

我需要从每一行(即Selective_draft_Law_Cases在第一线,List_of_songs_etc第二等的第一部分中提取标题)),并且它在一个MySQL表这是在同一行中的第三元素中的URL一起保存,iefor的first linesecond line

我还需要跳过该文件中的第一行,其有不同的,不相关的信息。

在PHP中完成这项工作的最快方法是什么?

注意:该文件相当大(超过1 GB的大小,超过600万行)。

在此先感谢!

+6

1. while loop 2. read line。 3.分割线。 4.插入行。 5.重复 – 2013-02-11 14:58:43

我相信它可以优化,但它的一个开始。请尝试:

function insertFileToDb(){ 
    $myFile = "myFile.txt"; //your txt file containing the data 
    $handle = fopen($myFile, 'r'); 

    //Read first line, but do nothing with it 
    $contents = fgets($handle); 

    //now read the rest of the file line by line 
    while(!feof($handle)){ 
     $data = fgets($handle); 

     //remove <> characters 
     $vowels = array("<", ">"); 
     $data = str_replace($vowels, "", $data); 

     //remove spaces to a single space for each line 
     $data = preg_replace('!\s+!', ' ', $data); 

     /* 
     * Get values from array, 1st URL is $dataArr[0] and 2nd URL is $dataArr[2] 
     * Explode on ' ' spaces 
     */ 
     $dataArr = explode(" ", $data); 

     //Get last part of uri from 1st element in array 
     $title = $this->getLastPartOfUrl($dataArr[0]); 

     //Execute your sql query with $title and $dataArr[2] which is the url 
     INSERT INTO `table` ... 
    } 
    fclose($handle); 
} 

function getLastPartOfUrl($url){ 
    $keys = parse_url($url); // parse the url 
    $path = explode("/", $keys['path']); // splitting the path 
    $last = end($path); // get the value of the last element 
    return $last; 
} 
+0

mallix,我试图测试你的代码,但遇到了一个障碍。文件中的第一行是“#started 2012-06-04T11:00:11Z”,它会引发错误。我如何让代码忽略第一行? – Phil 2013-02-12 09:00:12

+0

你没有提到这一点。您的帖子中没有“#”。先更新它。 – mallix 2013-02-12 10:44:31

+0

你是对的,已更新。 – Phil 2013-02-12 11:01:39

您应该使用正则表达式和使用PHP的preg_match功能,如果文件过大(这似乎是你的情况),您可能需要使用fopen + fgets + fclose以避免加载整个文件记忆和逐行工作。

您可以尝试测试file_get_contents对文件读取的性能,但由于需要大量内存,看起来这不会是更快的方式。