Chargement...

PHP import export CSV


CSV c'est quoi?

CSV ( pour Comma Separated Values ) qu'on pourrait traduire par "Valeurs séparées par des virgules" est un format de données où les valeurs sont comme son nom l'indique séparées par des virgules.

Ce format simple permet notamment de travailler sur des tableurs ( type Excel ) pour importer ou exporter des données d'un logiciel.

Exemple de format:
Nom,Prenom,Ville ENGEL,Olivier,New York Batman,Jean-Claude,Gotham Superman,Louis,Smallville
Qui resemblera visuellement dans votre tableur à ceci:
NomPrénomVille
ENGELOlivierNew York
BatmanJean-ClaudeGotham
SupermanLouisSmallville

Lire un fichier CSV avec PHP

<?php
$row = 1;
if (($handle = fopen("import.csv", "r")) !== FALSE):
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE):
$num = count($data);
echo "<br /><br /><p> $num champs à la ligne $row:</p>";
$row++;
for ($c=0; $c < $num; $c++):
echo $data[$c] . " | ";
endfor;
endwhile;
fclose($handle);
endif;
?>
Ce qui nous donnera :
3 champs à la ligne 1: Nom | Prenom | Ville | 3 champs à la ligne 2: ENGEL | Olivier | New York | 3 champs à la ligne 3: Batman | Jean-Claude | Gotham | 3 champs à la ligne 4: Superman | Louis | Smallville |

Ecrire un CSV

<?php
$list = array (
array( "Batman", "Gotham" ) ,
array( "Superman", "Smallville" ),
array( "Spiderman", "Paris" )
);
$fp = fopen("export.csv", "w");
foreach($list as $fields):
fputcsv($fp, $fields);
endforeach;
fclose($fp);
?>
Résultat:
Batman,Gotham Superman,Smallville Spiderman,Paris

Il est possible de créer un CSV à la volée comme ceci:

<?php
header("Content-Type: text/plain");
header("Content-disposition: attachment; filename=products.csv");

$out = fopen('PHP://output', 'w');
fputcsv($out, array(
"COL1",
"COL2",
"COL3"
));

foreach( $r as $row ):
    fputcsv($out, array(
    	$row['col1'],
    	$row['col1'],
    	$row['col1'],
    ));
endforeach;
fclose($out);
?>



Crée votre site web au meilleur prix💰


CSSW Apprendre à créer son site web