使用PHP将CSV文件中的单列转换为简单数组

4

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

简单地说,它们长这样:

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

这里有 3 万个电子邮件地址。

我需要使用 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列转换为数组?我已经进行了研究,但尚未找到解决方案。
2个回答

3
如果您的文件只有一列,您真的不需要使用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更快。你可以将其替换为上面的函数。

1

为什么不使用SplFileObject?我过去进行了一些基准测试,它比fgetcsv快大约2倍。

Here is a sample code:

/**
 * 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);

?>

Also, since your file contains only one column, you could just use file to retrieve the file content as an array. (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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接