2011-10-06 11 views
5

PHPでCSVファイルを読み取るには、いくつかの方法があります。 を使用して、関数を使用して各行を配列に入れ、次にが爆発してのコンマを使用し、のトリムを使用してデータの周りの引用符を削除してください。それはfgetcsvと* str_getcsv *は、今がありますPHP 5で...PHPがcsvファイルを効果的に読み取る

厄介だった...私はこれを推測している私は一緒にいくつかのコードをホイップしましたように、これらの日、それについて移動する最良の方法です。.. 。

$fp = fopen($csv_file['file_path'], 'r');  
while (($data = fgetcsv($fp, 0, "\r", '"', "\r")) !== FALSE) { 
    $num = count($data); 
    for ($c=0; $c < $num; $c++) { 
     print_r(str_getcsv($data[$c])); 
    } 
} 

もっとフェイルセーフなアプローチがありますか?例えば、改行が\ nか\ rのどちらであっても動作するようにする...

あなたが入力できるものはどれですか?

答えて

2

これは、CSVをネストされた配列に変換します。

<?php 
    /** 
    * 
    */ 
    function csv_entry_to_array(array $row) 
    { 
     $column_count = count($row); 
     $csv_column_values = array(); 

     // Loop through the columns of the current CSV entry and store its value 
     for ($column_index = 0; $column_index < $column_count; $column_index++) 
     { 
      // Store the value of the current CSV entry 
      $csv_column_values[] = $row[$column_index]; 
     } 

     // Return 
     return $csv_column_values;  
    } 

    /** 
    * @param string $input_file_name   Filename of input CSV 
    * @param boolean $include_header_in_output Flag indicating whether the first entry in the CSV is included in the output or not. 
    * @param integer $length      Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). 
    *            It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is 
    *            not limited, which is slightly slower. 
    * @param string $delimeter     Set the field delimiter (one character only). 
    * @param string $enclosure     Set the field enclosure character (one character only). 
    * @param string $escape      Set the escape character (one character only). Defaults as a backslash. 
    * $return array        Nested indexed array representing the CSV. Empty array on error (e.g. input file missing, input file not a CSV). 
    */ 
    function csv_file_to_array($input_file_name, $include_header_in_output = TRUE, $length = 1000, $delimeter = ',', $enclosure = '"', $escape = '\\') 
    { 
     // NOTE: this attempts to properly recognize line endings when reading files from Mac; has small performance penalty 
     ini_set('auto_detect_line_endings', TRUE); 

     $csv_array = array(); 

     // Warnings are supressed, but that's OK since the code handles such warnings 
     if (($handle = @fopen($input_file_name, "r")) !== FALSE) 
     { 
      $row_counter  = 0; 

      // Iterate over the CSV entries 
      while (($row = fgetcsv($handle, $length, $delimeter, $enclosure, $escape)) !== FALSE) 
      {   
       if ($row_counter === 0 && $include_header_in_output === TRUE) 
       { 
        // This is the first row in the CSV and it should be included in the output 
        $csv_array[] = csv_entry_to_array($row);     
       } 
       else if ($row_counter > 0) 
       { 
        // This is a row in the CSV that needs to be stored in the return array 
        $csv_array[] = csv_entry_to_array($row); 
       } 

       $row_counter++; 
      } 

      // Close file handler 
      fclose($handle); 
     } 
     else 
     { 
      // Input file: some error occured 
      return array(); 
     } 

     return $csv_array; 
    } 
+0

私も上記のMarioに言及しましたが、おそらく私のCSVファイルに何か問題があると思います... bensinclair.co/import.csvというファイルがあります。このファイルをコードで使用すると、次のようなデータが出力されます。上記のmariosコードで何が起こるのですか?img192.imageshack.us/img192/2483/screenshot20111006at123b.png MacのMicrosoft ExcelでCSVファイルを作成しました。間違ったことをやっているのですか、コード内で何かを調整する必要がありますか? –

+0

私は問題を見る。修正されます。 – StackOverflowNewbie

+0

コードを更新しました。 'ini_set( 'auto_detect_line_endings'、TRUE);を追加しました。試してみる。 – StackOverflowNewbie

6

ファイルをライン単位で読み取る機能があります。file()は、両方の改行タイプでも機能します。

全体CSVファイルを読み込むための最短の方法は次のとおりです。

$data = array_map("str_getcsv", file($filename)); 

ないあなた$num = count()は約何であったか確認してください。

+0

こんにちはマリオ、返信いただきありがとうございます。あなたが私に与えてくれたコードは、各セルを各行の代わりに1つの配列にして、それを自分の配列に入れます。だから私は今、その中のすべてのラインからすべてのセルを持つ大規模な配列を持っています。私は意味がありますか?どのようにして各行を独自の配列に分割できますか? –

+1

上記のスニペットは、一般的に想定されるテーブル構造である2次元の '$ data [$ line] [$ row]'を与えます。代わりにあなたが何を望むかは不明です。 - 各行を一回だけ見たい場合は、代わりにforeachを使います: 'foreach(file($ fn)as $ line){$ data = str_getcsv($ line);} } ' – mario

+0

私のCSVファイルに何か問題があると思います... http://bensinclair.co/import.csvのコイがあります...このファイルをあなたのコードと共に使用すると、このhttpのようなデータが出力されます://img192.imageshack.us/img192/2483/screenshot20111006at123b.png –

関連する問題