CodeHive

Developer's Articles, Tutorials, Code, Scripts Snippets and Examples.

PHP Array to CSV

PHP

What is CSV?

CSV, Comma Separated Values, is a type of file. Spreadsheets software like Excel and databases such as MySQL ,among many others, can import and export CSV files thus CSV files can be used to transfer data in between a large variety of programs.

PHP Array to CSV Function

/**
* Generatting CSV formatted string from an array.
* By Sergey Gurevich.
*/
function array_to_scv($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"')
{
	if (!is_array($array) or !is_array($array[0])) return false;
	
	//Header row.
	if ($header_row)
	{
		foreach ($array[0] as $key => $val)
		{
			//Escaping quotes.
			$key = str_replace($qut, "$qut$qut", $key);
			$output .= "$col_sep$qut$key$qut";
		}
		$output = substr($output, 1)."\n";
	}
	//Data rows.
	foreach ($array as $key => $val)
	{
		$tmp = '';
		foreach ($val as $cell_key => $cell_val)
		{
			//Escaping quotes.
			$cell_val = str_replace($qut, "$qut$qut", $cell_val);
			$tmp .= "$col_sep$qut$cell_val$qut";
		}
		$output .= substr($tmp, 1).$row_sep;
	}
	
	return $output;
}

PHP Array to CSV Function Input and Output

Input:

  • Array - Subject array.
  • Boolean - To display a header row of key values or not? (default value: true).
  • String - Column separator (default value: ",").
  • String - Row separator (default value: "\n" - newline).
  • String - Quote character, used for quoting data and escaping (default value: ").

Output:

  • Success - CSV formatted string.
  • Failure - Boolean false.

PHP Array to CSV function Usage and Result

Script:

//Subject array.
$array[] = array('key1' => 'row1-1', 'key2' => 'row1-2', 'key3' => 'row1-3', 'key4' => 'row1-4', 'key5' => 'row1-5');
$array[] = array('key1' => 'row2-1', 'key2' => 'row2-2', 'key3' => 'row2-3', 'key4' => 'row2-4', 'key5' => 'row2-5');
$array[] = array('key1' => 'row3-1', 'key2' => 'row3-2', 'key3' => 'row3-3', 'key4' => 'row3-4', 'key5' => 'row3-5');
$array[] = array('key1' => 'row4-1', 'key2' => 'row4-2', 'key3' => 'row4-3', 'key4' => 'row4-4', 'key5' => 'row4-5');

echo '<pre>';
print_r($array);
echo '</hr>';

//Converting array to SCV.
$csv_data = array_to_scv($array, false);
print_r($csv_data);


echo '</pre>';

Result:

Array
(
    [0] => Array
        (
            [key1] => row1-1
            [key2] => row1-2
            [key3] => row1-3
            [key4] => row1-4
            [key5] => row1-5
        )

    [1] => Array
        (
            [key1] => row2-1
            [key2] => row2-2
            [key3] => row2-3
            [key4] => row2-4
            [key5] => row2-5
        )

    [2] => Array
        (
            [key1] => row3-1
            [key2] => row3-2
            [key3] => row3-3
            [key4] => row3-4
            [key5] => row3-5
        )

    [3] => Array
        (
            [key1] => row4-1
            [key2] => row4-2
            [key3] => row4-3
            [key4] => row4-4
            [key5] => row4-5
        )

)
"row1-1","row1-2","row1-3","row1-4","row1-5"
"row2-1","row2-2","row2-3","row2-4","row2-5"
"row3-1","row3-2","row3-3","row3-4","row3-5"
"row4-1","row4-2","row4-3","row4-4","row4-5"




By Sergey Gurevich
great and simple. thanks.
It would be better if numeric values will not be quoted. When importing CSV to Office it matters - quoted values are treated as character strings and you can\'t apply eg. SUM() function to them.

In addition to that, you have misspelled function name: array_to_scv should be array_to_csv ;) Nice work however :)
Thanks. Saved me about 15 minutes scripting time. Keeping this in my tool drawer.
Thanks man !!! Nice work
Works just fine !
Thanks man!! awesome work
cool... Very useful. awesome.
what is the difference between this and
foreach ($myArray AS $value)
{
implode(\'\",\"\', $value);
}
without those escape characters
the values are coming. but i need to print the key value also.
how to do it?
A family member recommended me to this resource. Thank you for the information.
how to do if want to export as CSV from second column of data ?
You misspelled the function name using scv instead of csv :)

Thanks for the function!
Name:
Mail:
Website:
Accepting BBCode ([b]...[/b], [i]...[/i]).
Please copy this code to the input below. Get a different security code.
Please copy the letters from the image, making sure you are a meatbag.
Security Code:
There are no numbers, only letters.
Sergey Gurevich

Web Developer. Coding top notch internet technologies: PHP, MySQL, HTML, CSS, JavaScript, Ajax and others.

Posting here, on CodeHive, scripts I find particularly useful.

Always looking for something new and interesting.

More... Contact
A Smartass Once Said

GRIMMET (n.)
A small bush from which cartoon characters dangle over the edge of a cliff.

- Douglas Adams & John Lloyd, The Meaning of Liff
Misc
Contact Us

Valid HTML 4.01 Transitional

Generated in 0.022 seconds