Example 1: php read csv to array
$lines =file('CSV Address.csv');
foreach($lines as $data)
{
list($name[],$address[],$status[])
= explode(',',$data);
}
Example 2: read csv php
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Example 3: php array to csv
Instead of writing out values consider using 'fputcsv()'.
This may solve your problem immediately.
function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
return stream_get_contents($f);
}
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));
Example 4: column of csv to array php
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
Example 5: php csv
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
Example 6: csv to array php
$csv = array_map('str_getcsv', file('data.csv'));