PHP/File Directory/CSV File
Содержание
fgetcsv.php
<source lang="html4strict">
<?php
$fh = fopen("s.csv", "r"); while (list($name, $email, $phone) = fgetcsv($fh, 1024, ",")) {echo "
$name ($email) Tel. $phone
";}
?>
</source>
Generating comma-separated data
<source lang="html4strict">
<?php $sales = array( array("Northeast",12.54),
array("All Regions",1597.34) );
$fh = fopen("sales.csv","w") or die("Can"t open sales.csv"); foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) { die("Can"t write CSV line"); }
} fclose($fh) or die("Can"t close sales.csv"); ?>
</source>
Making a CSV-formatted string
<source lang="html4strict">
function make_csv_line($values) {
foreach($values as $i => $value) { if ((strpos($value, ",") !== false) || (strpos($value, """) !== false) || (strpos($value, " ") !== false) || (strpos($value, "\t") !== false) || (strpos($value, "\n") !== false) || (strpos($value, "\r") !== false)) { $values[$i] = """ . str_replace(""", """", $value) . """; } } return implode(",", $values) . "\n";
}
</source>
Parsing CSV Strings
<source lang="html4strict">
<?php function parse_csv($string, $delim = ",", $quote=""") {
$new = str_replace("{$quote}{$quote}", $quote, $string); $matches = array(); preg_match_all("/\s*({$quote}?)(.*?)\\1\s*(?:{$delim}|$)/", $new, $matches); array_pop($matches[2]); return $matches[2];
} $str = "c "s""v""","s", "f\ny" "; $values = parse_csv($str);
echo ""; print_r($values); echo "";
?>
</source>
Printing comma-separated data
<source lang="html4strict">
<?php $sales = array( array("Northeast",12.54),
array("All Regions",12.34) );
$fh = fopen("php://output","w"); foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) { die("Can"t write CSV line"); }
} fclose($fh); ?>
</source>
Putting comma-separated data into a string
<source lang="html4strict">
<?php $sales = array( array("Northeast",12.54),
array("All Regions",1597.34) );
ob_start(); $fh = fopen("php://output","w") or die("Can"t open php://output"); foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) { die("Can"t write CSV line"); }
} fclose($fh) or die("Can"t close php://output"); $output = ob_get_contents(); ob_end_clean(); ?>
</source>
Read csv file
<source lang="html4strict">
<?php $fh = fopen("csvdata.csv", "rb"); if (! $fh) {
die("Can"t open csvdata.csv: $php_errormsg");
}
print "" . implode(" | ", $line) . " |
?>
</source>
Reading CSV data from a file
<source lang="html4strict">
<?php $fp = fopen("data.csv","r") or die("can"t open file");
print "".htmlentities($csv_line[$i])." | ";
fclose($fp) or die("can"t close file"); ?>
</source>
Tell the web client to view the CSV file in a seprate program
<source lang="html4strict">
header("Content-Disposition: attachment; filename="dishes.csv"");
</source>