Problem reading PHP CSV files

I am trying to read data from a.csv file to open it on a web page as text.

This is the first time I do this, and I have an unpleasant little problem.

My. The CSV file (which opens by default by Excel) has several lines, and I read it all as one long line.

like this:

$contents = file_get_contents("files/data.csv");

In this example file I made, there are 2 lines.

Paul Blueberryroad 85 us Flashlight, bag November 20, 2008, 16:39

Hellen Blueberryroad 85 us lens13mm, flashlight, bag, ExtraBatteries November 20, 2008, 16:41:32

But the line read by PHP is this:

Paul, Blueberryroad 85, us, flashlight, bag, November 20, 2008, 4:39 pm, Hellen, Blueberryroad 85, us, 13mm lens, flashlight, bag, ExtraBatteries, November 20, 2008, 16:41:32

I share it as follows:

list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);

, $name [] "" "". .

, $orderdate []

20 2008 , 4:39 . Hellen

, . - , , ?

: , :

, :

$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
  $contents[] = fgetcsv($fo,0,';');
}
fclose($fo);

- , CSV 2 , 2 1 . 2 - , - 0.

+3
5

fgetcsv(), CSV CSV. , str_getcsv() .

+11

file() , .

, - :

$rows = array();
$name = array();
$street = array();
$country = array();

$rows = file("file.csv");
foreach($rows as $r) {
    $data = explode(";", $r);
    $name[] = $data[0];
    $street[] = $data[1];
    $country[] = $data[2];
}
+1

, :

$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
  $contents[] = fgetcsv($fo,0,';');
}
fclose($fo);

- , CSV 2 , 2 1 . 2 - , - 0.

+1

fgetcsv .

, . -, ( ) ", PHP" ( , ?). PS: , TSV () CSV (coma).

Also, if you want to go this way, you need to split the first file in lines, then the lines in fields.

0
source

The best way is of course fgetcsv ().

$f = fopen ('test.csv', 'r');
while (false !== $data = fgetcsv($f, 0, ';'))
    $arr[] = $data;
fclose($f);

But if you have the contents in a variable and you want to split it, and str_getcsv is not available, you can use this:

function str_split_csv($text, $seperator = ';') {
    $regex = '#' . preg_quote($seperator) . '|\v#';
    preg_match('|^.*$|m', $text, $firstline);
    $chunks = substr_count($firstline[0], $seperator) + 1;
    $split = array_chunk(preg_split($regex, $text), $chunks);
    $c = count($split) - 1;
    if (isset($split[$c]) && ((count($split[$c]) < $chunks) || (($chunks == 1) && ($split[$c][0] == ''))))
        unset($split[$c]);
    return $split;
}
0
source

All Articles