[SPIP] +2.1.12
[velocampus/web/www.git] / www / plugins / auto / spip-bonux / inc / importer_csv.php
1 <?php
2 /**
3 * Plugin Spip-Bonux
4 * Le plugin qui lave plus SPIP que SPIP
5 * (c) 2008 Mathieu Marcillaud, Cedric Morin, Romy Tetue
6 * Licence GPL
7 *
8 * Fonctions de lecture d'un fichier CSV pour transformation en array()
9 *
10 */
11
12 if (!defined("_ECRIRE_INC_VERSION")) return;
13
14 include_spip('inc/charsets');
15
16 /**
17 * Based on an example by ramdac at ramdac dot org
18 * Returns a multi-dimensional array from a CSV file optionally using the
19 * first row as a header to create the underlying data as associative arrays.
20 * @param string $file Filepath including filename
21 * @param bool $head Use first row as header.
22 * @param string $delim Specify a delimiter other than a comma.
23 * @param int $len Line length to be passed to fgetcsv
24 * @return array or false on failure to retrieve any rows.
25 */
26
27 /**
28 * Importer le charset d'une ligne
29 *
30 * @param unknown_type $texte
31 * @return array
32 */
33 function importer_csv_importcharset($texte){
34 // le plus frequent, en particulier avec les trucs de ms@@@
35 $charset_source = 'iso-8859-1';
36 // mais open-office sait faire mieux, donc mefiance !
37 if (is_utf8($texte))
38 $charset_source = 'utf-8';
39 return importer_charset($texte,$charset_source);
40 }
41
42 /**
43 * enlever les accents des cles presentes dans le head,
44 * sinon ca pose des problemes ...
45 *
46 * @param string $key
47 * @return string
48 */
49 function importer_csv_nettoie_key($key){
50 return translitteration($key);
51 /*$accents=array('�','�','�','�','�',"�","�","'");
52 $accents_rep=array('e','e','e','a','u',"o","c","_");
53 return str_replace($accents,$accents_rep,$key);*/
54 }
55
56 /**
57 * Lit un fichier csv et retourne un tableau
58 * si $head est true, la premiere ligne est utilisee en header
59 * pour generer un tableau associatif
60 *
61 * @param string $file
62 * @param bool $head
63 * @param string $delim
64 * @param string $enclos
65 * @param int $len
66 * @return array
67 */
68 function inc_importer_csv_dist($file, $head = false, $delim = ",", $enclos = '"', $len = 10000) {
69 $return = false;
70 $handle = fopen($file, "r");
71 if ($handle){
72 if ($head) {
73 $header = fgetcsv($handle, $len, $delim, $enclos);
74 if ($header){
75 $header = array_map('importer_csv_importcharset',$header);
76 $header = array_map('importer_csv_nettoie_key',$header);
77 }
78 }
79 while (($data = fgetcsv($handle, $len, $delim, $enclos)) !== FALSE) {
80 $data = array_map('importer_csv_importcharset',$data);
81 if ($head AND isset($header)) {
82 foreach ($header as $key=>$heading) {
83 $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
84 }
85 $return[]=$row;
86 } else {
87 $return[]=$data;
88 }
89 }
90 fclose($handle);
91 }
92 return $return;
93 }
94