使用php读取文本文件,将内容存储到数据库

时间:2015-02-25 03:19:28

标签: php database csv explode

我有一个txt文件,数据类似于下面。我需要读取文件并使用php将内容存储在数据库中,我试图将该行爆炸并将其读入数组,但第7列本身包含","因此无法使用","正确地爆炸它。对此有任何帮助,如何做到这一点。

"MN", 2215," 309   ","4002 ",10,"10463","VAN TULL, GORDON     ",000003120,"  ",1, 2, 4, "Y" 
"MN", 2215," 309   ","4002 ",10,"10463","RODRIGUEZ, RANDY     ",000003120,"  ",1, 2, 4, "Y"

我正在尝试关注

$handle = fopen($filename, "r")


1) $line = fgetcsv($handle,",")
    this is not working as column 7th itself have "," in its value.

2)
   $Line = fgets($handle);
   $data=explode(",",$Line);
   if count($data)>13 
    // concatenating col 6 and 7

2 个答案:

答案 0 :(得分:0)

你没有提到你是如何尝试解析csv的,但我猜测你只是将它分成逗号。相反,请尝试fgetcsv

答案 1 :(得分:0)

至少有几种方式

  1. 简单的方法是用一些特殊字符替换所有必要的逗号并爆炸

  2. 位编程 - 使用正则表达式

    $contents = file_get_contents(__dir__.'/sample.txt');
    
    $rows = explode(PHP_EOL, $contents);
    
    foreach($rows as $row){
        $cols = preg_split('/,(?=(?:[^"]|"[^"]*")*$)/', $row);
        // do what you want to do with cols, which is an array of columns
    }