簡體   English   中英

使用PHP將單個列從CSV轉換為簡單數組

[英]Converting a single column from a CSV in to a simple array using PHP

我在一個沒有標題的列中有一個帶有電子郵件列表的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列轉換為數組嗎? 我一直在做我的研究,但尚未找到解決方案。

如果文件中只有一列,則實際上不需要使用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更快。 你可以用上面的代替。

你為什么不使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM