开发者

sort data for database php

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开发者_Go百科 new line and then exploding those results on a space be sufficient?


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 |.


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
}


Easiest way would probably be to use fgetcsv specifying a space character as your delimiter.


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);
?>


You can also use fgets() for reading each line and explode() on spaces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜