Any function to take an array of strings and return a CSV line?
I have an array of strings and want a way to create a CSV line from them. Something like:
$CSV_line = implode(',',$pieces);
Will not work as the pieces may contain comma and double quotes.
Is there a PHP built in function that takes the pieces and return a well formatted CSV line?开发者_如何转开发Thanks,
RogeIf you want to write that line to a file, you can use fputcsv
Using the streams functionnality of PHP, it should be possible to write to a variable -- indeed, there's one guy in the comments of str_getcsv
who posted his implementation of str_putcsv
:
<?php
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
// Open a memory "file" for read/write...
$fp = fopen('php://temp', 'r+');
// ... write the $input array to the "file" using fputcsv()...
fputcsv($fp, $input, $delimiter, $enclosure);
// ... rewind the "file" so we can read what we just wrote...
rewind($fp);
// ... read the entire line into a variable...
$data = fread($fp, 1048576); // [changed]
// ... close the "file"...
fclose($fp);
// ... and return the $data to the caller, with the trailing newline from fgets() removed.
return rtrim( $data, "\n" );
}
?>
Note : this code is not mine -- it's a copy-paste of the one posted by Ulf on php.net.
You could even write a Class to do this
class CSV_ARRAY {
static public function arr_to_csv_line($arr) {
$line = array();
foreach ($arr as $v) {
$line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"';
}
return implode(",", $line);
}
static public function arr_to_csv($arr) {
$lines = array();
foreach ($arr as $v) {
$lines[] = self::arr_to_csv_line($v);
}
return implode("\n", $lines);
}
}
you could useit like this
$csvlines = CSV_ARRAY::arr_to_csv_line($myarray);
file_put_contents($csvlines,"mycsv.csv");
thats it ;-)
As far as I know there is no such built in function. The one I'm aware of is fputcsv that does exactly what you want but it does not return the CSV line, but writes it to a file.
<?php
$pieces = array (
'a,b,c,d', // contains comma.
'"1","2"' // contains double quotes.
);
$fp = fopen('file.csv', 'w');
fputcsv($fp, $pieces); // "a,b,c,d","""1"",""2""" written
fclose($fp);
?>
Most of the times you want create the line of CSV and write it to the file. So the above function should suffice.
I'd written one such function for PHP4 as it does not support fputcsv. I'll share it with you:
// If a value contains a comma, a quote, a space, a tab, a newline, or a linefeed,
// then surround it with quotes and replace any quotes inside it with two quotes
function make_csv_line($values)
{
// iterate through the array ele by ele.
foreach($values as $key => $value)
{
// check for presence of special char.
if ( (strpos($value, ',') !== false) || (strpos($value, '"') !== false) ||
(strpos($value, ' ') !== false) || (strpos($value, "\t") !== false) ||
(strpos($value, "\n") !== false) || (strpos($value, "\r") !== false))
{
// if present, surround the ele in quotes..also replace
// already existing " with ""
$values[$key] = '"' . str_replace('"', '""', $value) . '"';
}
}
// now create the CSV line by joining with a comma, also put a \n at the end.
return implode(',', $values) . "\n";
}
Here is a simpler fputcsv implementation:
$stdout = fopen('php://output','w'); // 'stdout' is for CLI, 'output' is for Browser
fputcsv($stdout, array('val,ue1','val"ue2','value3','etc'));
fflush($stdout); // flush for fun :)
fclose($stdout);
I snarfed this elswhere on SO and posted here for faster reference, please bump/credit the original posting: Is my array to csv function correct?
Well, the thing is, there is no well formatted CSV. For instance, Open Office uses the semicolon (;) as default delimiter, while Excel expects it to be a comma (,). But fact is, no standard exists.
Assuming the Array looks something like this:
Array
0 => Some string
1 => Some other string, with comma
2 => And a third one with "double quotes"
);
You could either use implode with a different delimiter, e.g.
$delimiter = chr(9); // Tab
$delimiter = ';' // Semicolon. Excel's default
$delimiter = '|' // Pipe
$delimiter = "','"; // Comma plus Single Quote
If that is not working, run the String array through array_filter
first and change the double quotes and comma via callback to whatever you think they should be, before exploding with just a comma delimiter:
$csv = implode(',' array_filter($array, 'my_csv_prepare'));
But keep in mind, this does not guarantee your consuming application to be able to read the CSV. It really depends on how they implemented CSV parsing. Like I said: no standard.
精彩评论