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

时间:2013-02-11 14:56:54

标签: php mysql

我有从dbpedia下载的文件,其内容如下所示:

<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等)中提取标题,并将其与第三个URL一起保存在mysql表中同一行中的元素,即first line 对于second line

我还需要跳过文件中包含不同无关信息的第一行。

在PHP中完成此操作的最快方法是什么?

注意:文件非常大(超过1 GB,超过600万行)。

提前致谢!

2 个答案:

答案 0 :(得分:1)

你应该使用正则表达式并使用PHP的preg_match函数,如果文件太大(这似乎是你的情况),你可能想要使用fopen + {{3 +} fgets以避免将整个文件加载到内存中并逐行工作。

您可以尝试测试fclose的性能来读取文件,但由于需要大量内存,这似乎不是更快的方法。

答案 1 :(得分:1)

我确信它可以优化,但它是一个开始。尝试:

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;
}
相关问题