Reputation: 19837
hey say I have a file containing something like this
name1 lastname1 email1 date1
name2 lastname2 email2 date2
name3 lastname3 email3 date3
what would the most efficient way to go through it to retrieve the first name last name email and date be? Would just exploding on a new line and then exploding those results on a space be sufficient?
Upvotes: 1
Views: 135
Reputation: 5303
What's the size of your file ? Different approach is needed, regarding simplicity of the code
VS memory usage
.
If it is a medium file (small, use the file
function :
// file : Reads entire file into an array
$fileAsArray = file($filname);
foreach($fileAsArray as $line){
list($name,$lastname,$email,$date) = explode(" ",$line);
//do something with $name,$lastname,$email,$date
}
Upvotes: 3
Reputation: 237865
Your data is effectively a CSV file, using a space character as a delimiter. You can use fgetcsv
and set the delimiter option:
$fh = fopen('data.csv', 'r');
while ($row = fgetcsv($fh, 0, ' ')) {
// $row[0] is firstname
// $row[1] is lastname
// $row[2] is email
// $row[3] is date
}
It would probably be a better idea to use a different character for delimiting, such as a comma, a tab, or a pipe |
.
Upvotes: 3
Reputation: 4827
You can also use fgets()
for reading each line and explode()
on spaces.
Upvotes: 1
Reputation: 60498
Easiest way would probably be to use fgetcsv specifying a space character as your delimiter.
Upvotes: 2
Reputation: 3947
if it's a CSV file, use fgetcsv().
Assuming the separator is the TAB character :
<?php
$keys = array('name1', 'lastname1', 'email1', 'date1');
$entries = array();
$fh = fopen("test.csv", "r");
while ($data = fgetcsv($fh, 1000, "\t")) {
$entries = array_combine($keys, $data);
}
fclose($fh);
var_dump($entries);
?>
Upvotes: 1