Use numpy. loadtxt() to Read a CSV File Into an Array in Python. As the name suggests, the open() function is used to open the CSV file. NumPy's loadtxt() function helps in loading the data from a text file.
The fgetcsv() function parses a line from an open file, checking for CSV fields.
Description ¶ Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. Note: The locale settings are taken into account by this function.
You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==
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.
I think the str_getcsv() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system.
$csv = str_getcsv(file_get_contents('myCSVFile.csv'));
echo '<pre>';
print_r($csv);
echo '</pre>';
Or for a line by line solution:
$csv = array();
$lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
Or for a line by line solution with no str_getcsv():
$csv = array();
$file = fopen('myCSVFile.csv', 'r');
while (($result = fgetcsv($file)) !== false)
{
$csv[] = $result;
}
fclose($file);
echo '<pre>';
print_r($csv);
echo '</pre>';
I have created a function which will convert a csv string to an array. The function knows how to escape special characters, and it works with or without enclosure chars.
$dataArray = csvstring_to_array( file_get_contents('Address.csv'));
I tried it with your csv sample and it works as expected!
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// @author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {
$char = $string{$i};
$addChar = "";
if($isEnclosured) {
if($char==$enclosureChar) {
if($i+1<$size && $string{$i+1}==$enclosureChar){
// escaped char
$addChar=$char;
$i++; // dont check next char
}else{
$isEnclosured = false;
}
}else {
$addChar=$char;
}
}else {
if($char==$enclosureChar) {
$isEnclosured = true;
}else {
if($char==$separatorChar) {
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex++;
}elseif($char==$newlineChar) {
echo $char;
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}else {
$addChar=$char;
}
}
}
if($addChar!=""){
$fieldValue.=$addChar;
}
}
if($fieldValue) { // save last field
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
$arrayFromCSV = array_map('str_getcsv', file('/path/to/file.csv'));
Old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I've written a small function that works with fgetcsv itself.
Below is my function from https://gist.github.com/4152628:
function parse_csv_file($csvfile) {
$csv = Array();
$rowcount = 0;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
$max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
$header = fgetcsv($handle, $max_line_length);
$header_colcount = count($header);
while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
$row_colcount = count($row);
if ($row_colcount == $header_colcount) {
$entry = array_combine($header, $row);
$csv[] = $entry;
}
else {
error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
return null;
}
$rowcount++;
}
//echo "Totally $rowcount rows found\n";
fclose($handle);
}
else {
error_log("csvreader: Could not read CSV \"$csvfile\"");
return null;
}
return $csv;
}
Returns
Begin Reading CSV
Array
(
[0] => Array
(
[vid] =>
[agency] =>
[division] => Division
[country] =>
[station] => Duty Station
[unit] => Unit / Department
[grade] =>
[funding] => Fund Code
[number] => Country Office Position Number
[wnumber] => Wings Position Number
[title] => Position Title
[tor] => Tor Text
[tor_file] =>
[status] =>
[datetime] => Entry on Wings
[laction] =>
[supervisor] => Supervisor Index Number
[asupervisor] => Alternative Supervisor Index
[author] =>
[category] =>
[parent] => Reporting to Which Position Number
[vacant] => Status (Vacant / Filled)
[index] => Index Number
)
[1] => Array
(
[vid] =>
[agency] => WFP
[division] => KEN Kenya, The Republic Of
[country] =>
[station] => Nairobi
[unit] => Human Resources Officer P4
[grade] => P-4
[funding] => 5000001
[number] => 22018154
[wnumber] =>
[title] => Human Resources Officer P4
[tor] =>
[tor_file] =>
[status] =>
[datetime] =>
[laction] =>
[supervisor] =>
[asupervisor] =>
[author] =>
[category] => Professional
[parent] =>
[vacant] =>
[index] => xxxxx
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With