PHP files and CSV files


php file open, file fputcsv, file fgetcsv and file close example

fputcsv example
$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aa"a"', ',"bb\""b"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

$fp = fopen('file.csv', 'r');

while ($list = fgetcsv($fp)) {
    foreach ($list as $fields) {
        echo $fields.", ";
    }
    echo PHP_EOL;
}

fclose($fp);



fgetcsv example
$fh = fopen($filename,'r');

while (($row=fgetcsv($fh))!==FALSE)
{
    echo count($rows).PHP_EOL;
}

fclose($fh);


or if you require additional CSV pre-processing then try

str_getcsv example
if (!function_exists('str_getcsv'))
  {
  function str_getcsv($input, $delimiter=null, $enclosure=null, $escape=null) {
    $temp=fopen("php://memory", "rw");
    fwrite($temp, $input);
    fseek($temp, 0);
    $r=fgetcsv($temp);
    fclose($temp);
    return $r;
  }
}

$fh = fopen($filename,'r');

while (($s=fgets($fh))!==FALSE)
{
    $s = str_replace('mypreprocFROM', 'mypreprocTO', $s);
    $row = str_getcsv($s)
    echo count($row).PHP_EOL;
}

fclose($fh);



REFERRERS
PearFileCsv
PhpFunctions
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki