Freelance of Dev biznet
6/5/2019 - 12:52 PM

Array to CSV en PHP

Fonction pour transformer un tableau PHP (array) en CSV. Exemple d'un export CSV d'un repeater ACF (second fichier).

<?php
  function array_to_csv_download($arrayCan, $filename = 'candidature.csv', $delimiter = ";") {
		header('Content-Encoding: UTF-8');
		header('Content-type: text/csv; charset=UTF-8');
		// header('Content-Type: application/csv');
		header('Content-Disposition: attachement; filename="'.$filename.'";');

		$f = fopen('php://output', 'w');
	
		// error_reporting(0);
		echo "\xEF\xBB\xBF";

		foreach ($arrayCan as $line) {
			fputcsv($f, $line, $delimiter);
		}
	}
?>
<?php
	$path = $_SERVER['DOCUMENT_ROOT'];

	include_once $path . '/wp-config.php';
	include_once $path . '/wp-load.php';
	include_once $path . '/wp-includes/wp-db.php';
	include_once $path . '/wp-includes/pluggable.php';
		
	$arrayCSV = array();
	
	array_push($arrayCSV, array(
		'enseigne' => 'Enseigne', 
		'reseaux' => 'Réseau',
		'nom' => 'Magasin',
		'adresse' => 'Adresse',
		'salarie' => 'Salarié',
		'email' => 'Email',
		'telephone' => 'Téléphone',
		'date' => 'Date'
	));
	
	while ( have_rows('inscriptions', 3404) ) {
		the_row();

		array_push($arrayCSV, array(
			'enseigne' => get_sub_field('enseigne'), 
			'reseaux' => get_sub_field('reseaux'),
			'nom' => get_sub_field('nom'),
			'adresse' => get_sub_field('adresse'),
			'salarie' => get_sub_field('salarie'),
			'email' => get_sub_field('email'),
			'telephone' => get_sub_field('telephone'),
			'date' => get_sub_field('date')
		));
	}
	
	array_to_csv_download($arrayCSV, 'export_challenge_pavillon_france_pro_'.date('Ymd').'.csv');	
?>