1

If I have a text file:

Ramon,19,Libra   
Renata,25,Aries   
Roxy,52,Leo

If I am to create an array:

print_r(explode(",", $str));

How do I account for the newlines?

3 Answers3

5

Depends on what you want, but try file():

$lines = file('/path/to/file.txt');
foreach($lines as $line) {
    $data[] = explode(',', $line);
}
print_r($data);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
5

Another good way is use str_getcsv

foreach(file('/path/to/file.txt') as $line) {
    $data[] = str_getcsv($line);
}

var_dump($data);

And returns:

Array
(
    [0] => Array
        (
            [0] => Ramon
            [1] => 19
            [2] => Libra
        )

    [1] => Array
        (
            [0] => Renata
            [1] => 25
            [2] => Aries
        )

    [2] => Array
        (
            [0] => Roxy
            [1] => 52
            [2] => Leo
        )

)

Or you can use the fgetcsv function

mcuadros
  • 4,098
  • 3
  • 37
  • 44
  • This looks like a standard csv, str_getcsv method can handle several formats. – mcuadros Nov 25 '13 at 22:49
  • I like this better, my file had quoted text, like "Roxy","52","Leo" and the parsed values included the quotation marks, so $data = '"Roxy"'. Using fgetcsv() removed the string delimiters. – crafter May 14 '16 at 20:01
3

just another way it could be done

$filestring = file_get_contents('...path to file...');
$lines = explode(PHP_EOL,$filestring);
foreach($lines as $line) {
     $data[] = explode(',', $line);
}
print_r($data);
John Ezell
  • 72
  • 2