Reputation: 1297
I've got a csv with a list of emails in a single column with no header.
Very simply, they're like this:
[email protected]
[email protected]
[email protected]
...etc
And there are 30k of them.
I need to convert this list of emails in to a simple array using PHP.
I understand the concept of fgetcsv()
but as we know it reads a row at a time, so what I end up with is several arrays by iterating through my csv instead of one.
I need this:
Array
(
[0] => [email protected]
[1] => [email protected]
[2] => [email protected]
)
What I'm getting is this:
Array
(
[0] => [email protected]
)
Array
(
[0] => [email protected]
)
Array
(
[0] => [email protected]
)
Here's my code:
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);
}
Is there a simple way of simply converting a whole CSV column in to an array using PHP? I've been doing my research but have yet to find a solution.
Upvotes: 4
Views: 2848
Reputation: 1103
If you have only one column in your file, you really don't need to use fgetcsv. You could use the fgets function (https://www.php.net/manual/en/function.fgets.php) instead. This function returns a string, which you could easily add to your array like so:
$emails = array();
if (($file = fopen("emails.csv", "r")) !== FALSE) {
while (($email = fgets($file)) !== FALSE) {
$emails[] = $email;
}
fclose($file);
}
Alternatively, if you insist upon using fgetcsv, you could alter your code as follows:
$emails = array();
if (($file = fopen("emails.csv", "r")) !== FALSE) {
while (($arr = fgetcsv($file)) !== FALSE) {
$emails[] = $arr[0];
}
fclose($file);
}
Finally, I have read, but not tested myself, that the stream_get_line function (http://www.php.net/manual/en/function.stream-get-line.php) is even faster than fgets. You could substitute it above.
Upvotes: 3
Reputation: 17062
Why don't you use SplFileObject
? I've done some benchmarking in the past and it's around 2 times faster than fgetcsv
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);
Upvotes: 1