Puddinq.com sharing knowledge
';

Excel csv – snippet

Excel csv - snippet

This function writes a csv file to the folder it is run in.

function main() {
	echo "<br>\n<br>\n<br>\n<br>\nHello, there";


	if (!ini_get("auto_detect_line_endings")) {
		ini_set("auto_detect_line_endings", '1');
	}

	// create

	$list = array (
		array('aaa', 'bbb', 'ccc', 'dddd'),
		array('123', '456', '789'),
		array('"aaa"', '"bbb"')
	);

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

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

	fclose($fp);

	// read
	$row = 1;
	if (($handle = fopen("file.csv", "r")) !== FALSE) {
		while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
			echo '<pre>';
			print_r($data);
			echo '</pre>';
			
			$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);
	}

}