How to Create an Array from a CSV File Using PHP and the Fgetcsv Function

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

How to create an array from a CSV file using PHP but NOT using fgetcsv

You don't need another function; just use fgetcsv() properly - the default separator is a , and your file has ; as the separator, so you need to tell fgetcsv() that little fact:

$line_of_text[] = fgetcsv($file_handle, 1024, ';');

then it will work for you

Convert CSV into Array

Look into fgetcsv()

<?php

$handle = fopen("test.csv", "r");
$result = Array();
fgetcsv($handle); //Removes the first line of headings in the csv
while($data = fgetcsv($handle)) {
$result[$data[0]] = $data[1];
}
print_r($result); //the result
?>

Read lines of CSV file and put values into an Array

Ok so i got it.

I dont know why, but this code adds a " to the final of each line in my file like i said before. Ofcourse i did a test with the enclosure ($line = fgetcsv($file, 0, '|', ' " ') and nothing.
Since i was desperate i inverted the enclosure and i did ($line = fgetcsv($file, 0, '|', " ' ") and it works.
I don't know why PHP is treating the ' as a " but ok. Well it works now so hope this might help anyone in same situation. Here is full code:

while (($line = fgetcsv($file, 0, '|', "'")) !== FALSE) {

$OrderLines[] = $line;
}
fclose($file);

PHP CSV string to array

Do this:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);

It will give you an output like this:

Array
(
[0] => Array
(
[0] => 12345
[1] => Computers
[2] => Acer
[3] => 4
[4] => Varta
[5] => 5.93
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)

[1] => Array
(
[0] => 12346
[1] => Computers
[2] => Acer
[3] => 5
[4] => Decra
[5] => 5.94
[6] => 1
[7] => 0.04
[8] => 27-05-2013
)

)

I hope this can be of some help.

Display csv file in array

If that's your expected output at the top you can simply use file() method to parse the file into an array.

$lines = file('file.csv');

foreach ($lines as $line_num => $line) {
echo $line . '<br />';
}

Looping through a csv with fgetcsv

The first example in the fgetcsv() documentation contains the nuggets of what you need.

$file = fopen("testEmails.csv","r");

while (($data = fgetcsv($file)) !== FALSE)
{
echo "email address " . $data[0];
}

fgetcsv() returns a numerically indexed array of representing the columns, so you just want to print the first column.

Keep Integer and Float Types When Converting CSV Data to PHP Arrays With str_getcsv and fgetcsv

Seems like unfortunately there is no other way than doing a workaround! There are some options to do it and there is not "the one way to go". Depending to each usecase there might be different solutions. For my situation I will use the following code.

<?php
$csv = '0,1.2,"string"';
json_decode( "[$csv]", true );

But be aware that this will fail with multiline values at least!

Here are some tests:

<?php
$csv = '0,1.2,"string"';
var_dump(
json_decode( "[$csv]", true ) // works
, str_getcsv( $csv ) // converts everything to string
);
/*
array(3) { json_decode
[0]=>int(0)
[1]=>float(1.2)
[2]=>string(6) "string"
}
array(3) { str_getcsv
[0]=>
string(1) "0"
[1]=>
string(3) "1.2"
[2]=>
string(6) "string"
}
*/
$csv = '", as value in ,-separated csv"';
var_dump(
json_decode( "[$csv]", true ) // works also when separator is part of value
, str_getcsv( $csv ) // works also when separator is part of value but converts everything to string
);
/*
array(1) { json_decode
[0]=>string(29) ", as value in ,-separated csv"
}
array(1) { str_getcsv
[0]=>string(29) ", as value in ,-separated csv"
}
*/
$csv = '0,"value
with multiline"';
var_dump(
json_decode( "[$csv]", true ) // doesn't work as JSON can't handle multilines
, str_getcsv( $csv ) // works also with multilines but converts everything to string
);
/*
NULL json_decode
array(2) { str_getcsv
[0]=>string(1) "0"
[1]=>string(21) "value
with multiline"
}
*/

A very robust way seems to be the version from my original question as it relies on the native str_getcsv-function and converts to appropriate types back afterwards. Performancewise this doesn't sound ideal to me but this should be only a concern when dealing with very heavy strings (which is the case for me).

<?php
$csv = str_getcsv('0,1.2,"string"');
foreach ( $csv as &$v ) if ( is_numeric( $v ) ) $v += 0;


Related Topics



Leave a reply



Submit