【问题标题】:Converting a single column from a CSV in to a simple array using PHP使用 PHP 将单个列从 CSV 转换为简单数组
【发布时间】:2014-04-02 23:03:45
【问题描述】:

我有一个 csv,其中有一列没有标题的电子邮件列表。

很简单,它们是这样的:

example@123.com
email@somewhere.com
helloworld@email.org

...等

其中有 30k 个。

我需要使用 PHP 将这个电子邮件列表转换为一个简单的数组。

我了解fgetcsv() 的概念,但我们知道它一次读取一行,所以我最终得到的是通过迭代我的 csv 而不是一个数组来获得多个数组。

我需要这个:

Array
(
    [0] => example@123.com
    [1] => email@somewhere.com
    [2] => helloworld@email.org
)

我得到的是这样的:

Array
(
    [0] => example@123.com
)

Array
(
    [0] => email@somewhere.com
)

Array
(
    [0] => helloworld@email.org
)

这是我的代码:

if (($file = fopen("emails.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($file)) !== FALSE) {
          // do stuff
    }

    echo '<pre>';
    print_r($data);
    echo '</pre>';
    echo '<br/>';   

    fclose($file);  
}

有没有一种简单的方法可以使用 PHP 将整个 CSV 列转换为数组?我一直在做我的研究,但还没有找到解决方案。

【问题讨论】:

    标签: php arrays csv fgetcsv


    【解决方案1】:

    如果您的文件中只有一列,则确实不需要使用 fgetcsv。您可以改用 fgets 函数 (http://us2.php.net/manual/en/function.fgets.php)。此函数返回一个字符串,您可以像这样轻松地将其添加到数组中:

    $emails = array();
    if (($file = fopen("emails.csv", "r")) !== FALSE) {
        while (($email = fgets($file)) !== FALSE) {
             $emails[] = $email;
        }
        fclose($file);  
    }
    

    或者,如果您坚持使用 fgetcsv,您可以按如下方式更改您的代码:

    $emails = array();
    if (($file = fopen("emails.csv", "r")) !== FALSE) {
        while (($arr = fgetcsv($file)) !== FALSE) {
             $emails[] = $arr[0];
        }
        fclose($file);  
    }
    

    最后,我已经读过,但没有自己测试过,stream_get_line 函数 (http://www.php.net/manual/en/function.stream-get-line.php) 甚至比 fgets 还要快。你可以在上面替换它。

    【讨论】:

      【解决方案2】:

      为什么不使用SplFileObject?我过去做过一些基准测试,它比 fgetcsv 快 2 倍左右

      这是一个示例代码:

      /**
       * Get the CSV file as a SplFileObject so we could easily process it afterwards.
       */
      $file = '/path/to/my/file.csv';     
      $delimiter = ',';
      $csv_file = new SplFileObject($file);
      $csv_file->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
      $csv_file->setCsvControl($delimiter);
      
      /**
       * Process each line from the CSV file
       */
      while ($csv_file->current() !== false) {
          $count++;
          $lines[] = trim($csv_file->current());
          $csv_file->next();
      }
      
      var_dump($lines);
      
      ?>
      

      此外,由于您的文件仅包含一列,您可以使用file 将文件内容作为数组检索。 (http://www.php.net/manual/en/function.file.php)

      // Get a file into an array.  In this example we'll go through HTTP to get
      // the HTML source of a URL.
      $lines = file('/path/to/file.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      

      【讨论】:

        猜你喜欢
        • 2016-02-05
        • 2019-11-07
        • 1970-01-01
        • 2020-04-19
        • 1970-01-01
        • 2014-11-19
        • 2020-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多