IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
logo
Sommaire > Tableaux (Array)
        Enregistrer un tableau php en Fichier SYLK compatible Excel
        Afficher un tableau à plusieurs dimensions dans une table HTML
        Représentation personalisable d'objets et tableaux
        Un print_r() amélioré

rechercher
precedent    sommaire    suivant    telecharger


Auteur : Atchoum
Version : 11/01/2006
Enregistrer un tableau php en Fichier SYLK compatible Excel
L'avantage par rapport au CSV c'est qu'il gère la taille des colonnes et il met le titre en gras.
function sylk($tableau,$nomfic)
{
   define("FORMAT_REEL",   1); // #,##0.00
   define("FORMAT_ENTIER", 2); // #,##0
   define("FORMAT_TEXTE",  3); // @
   $cfg_formats[FORMAT_ENTIER] = "FF0";
   $cfg_formats[FORMAT_REEL]   = "FF2";
   $cfg_formats[FORMAT_TEXTE]  = "FG0";
   if ($tableau)
   {
      // en-tête du fichier SYLK
      if ($nomfic==false)
         $nomfic="extraction";
      $myfile= fopen($nomfic.".xls","w+")or die("pas bien");
      fputs($myfile,"ID;Atchoum Production\n"); // ID;Pappli
      fputs($myfile,"\n");
      // formats
      fputs($myfile,"P;PGeneral\n");     
      fputs($myfile,"P;P#,##0.00\n");       // P;Pformat_1 (reels)
      fputs($myfile,"P;P#,##0\n");          // P;Pformat_2 (entiers)
      fputs($myfile,"P;P@\n");              // P;Pformat_3 (textes)
      fputs($myfile,"\n");
      // polices
      fputs($myfile,"P;EArial;M200\n");
      fputs($myfile,"P;EArial;M200\n");
      fputs($myfile,"P;EArial;M200\n");
      fputs($myfile,"P;FArial;M200;SB\n");
      fputs($myfile,"\n");
      // nb lignes * nb colonnes :  B;Yligmax;Xcolmax
      fputs($myfile,"B;Y".(count($tableau)));
      // detection du nb de colonnes
      
      for($i=0;$i < count($tableau) ;$i++)
         $tmp[$i]=count($tableau[$i]);
      $nbcol=max($tmp);
      fputs($myfile,";X".$nbcol."\n");
      fputs($myfile,"\n");
      // récupération des infos de formatage des colonnes
      for($cpt=0; $cpt< $nbcol;$cpt++)
      {
         switch(gettype($tableau[1][$cpt]))
         {
            case "integer":
               $num_format[$cpt]=FORMAT_ENTIER;   
            $format[$cpt]= $cfg_formats[$num_format[$cpt]]."R";
            break;
            case "double":
               $num_format[$cpt]=FORMAT_REEL;   
            $format[$cpt]= $cfg_formats[$num_format[$cpt]]."R";
            break;
            default:
            $num_format[$cpt]=FORMAT_TEXTE;   
            $format[$cpt]= $cfg_formats[$num_format[$cpt]]."L";
            break;
         }   
      }
      // largeurs des colonnes
      for ($cpt = 1; $cpt <= $nbcol; $cpt++)
      {
         for($t=0;$t < count($tableau);$t++)
            $tmpo[$t]= strlen($tableau[$t][$cpt-1]);
         $taille=max($tmpo);
         // F;Wcoldeb colfin largeur
         if (strlen($tableau[0][$cpt-1]) > $taille)
            $taille=strlen($tableau[0][$cpt-1]);
         if ($taille>50)
            $taille=50;
         fputs($myfile,"F;W".$cpt." ".$cpt." ".$taille."\n");
      }
      fputs($myfile,"F;W".$cpt." 256 8\n"); // F;Wcoldeb colfin largeur
      fputs($myfile,"\n");
      // en-tête des colonnes (en gras --> SDM4)
      for ($cpt = 1; $cpt <= $nbcol; $cpt++)
      {
         fputs($myfile,"F;SDM4;FG0C;".($cpt == 1 ? "Y1;" : "")."X".$cpt."\n");
         fputs($myfile,"C;N;K\"".$tableau[0][$cpt-1]."\"\n");
      }
      fputs($myfile,"\n");
      // données utiles
      $ligne = 2;
      for($i=1;$i< count($tableau);$i++)
      {
         // parcours des champs
         for ($cpt = 0; $cpt < $nbcol; $cpt++)
         {
            // format
            fputs($myfile,"F;P".$num_format[$cpt].";".$format[$cpt]);
            fputs($myfile,($cpt == 0 ? ";Y".$ligne : "").";X".($cpt+1)."\n");
            // valeur
            if ($num_format[$cpt] == FORMAT_TEXTE)
               fputs($myfile,"C;N;K\"".str_replace(';', ';;', $tableau[$i][$cpt])."\"\n");
            else
               fputs($myfile,"C;N;K".$tableau[$i][$cpt]."\n");
         }
         fputs($myfile,"\n");
         $ligne++;
      }
      // fin du fichier
      fputs($myfile,"E\n");
      fclose($myfile);
   }else
      print "fichier non créer<br>";
}

Auteur : doof
Version : 11/01/2006
Afficher un tableau à plusieurs dimensions dans une table HTML
function array_show($tabl)
{
   static $taille;
   echo "<table border=1 cellspacing=0 cellpadding=0 $taille>";
   if (is_array($tabl)) {
      $nbclées=sizeof($tabl);
      $keyscol=array_keys($tabl);
      $firstcol1=$keyscol[0];
      $test2d=$tabl[$firstcol1];
      if (is_array($test2d)) {
         echo "<tr><td bgcolor=efeffb><b>clés</b></td>";
         foreach ($tabl as $clee => $valeur) {
            echo "<td align=center bgcolor=efeffb><b> $clee </b></td>";
         }
         echo "<tr>";
         foreach ($tabl[$firstcol1] as $ligne => $valeur) {
            echo "<tr><td align=center bgcolor=efefef><b>$ligne</b></td>";
            foreach ($tabl as $col => $val) {
               $case=$tabl[$col][$ligne];
               if (is_array($case)) {
                  $taille="width=100% height=100%";
                  echo "<td>";
                  array_show($tabl[$col][$ligne]);
                  echo "</td>";
               }
               else {
               echo "<td align=center>".$case."</td>";
               }
            }
            echo "</tr>";
         }
      }
      else {
         foreach ($tabl as $clee => $value) {
            if (!is_array($value)) {
               echo "<tr><td align=center bgcolor=efefef width=15><b> $clee </b></td>
   <td align=center>$value</td>";
            }
            else {
               $taille="width=100% height=100%";
               echo "<td bgcolor=efeffb align=center colspan=2><b>$clee</b></td>";
               array_show($tabl[$clee]);
               echo "</td>";
            }
            echo "</tr>";
         }
      }
   }
   else {
      echo "$tabl (variable simple)<br><br>";
   }
   echo "</table>";
   $taille="";
}

Auteur : doof
Version : 16/01/2006
Représentation personalisable d'objets et tableaux
Cette fonction prend en paramètre un objet ou un tableau pour le parcourir récursivement et
retourner le contenu formaté grace à sprintf(),donc personalisable.

Le 2eme paramètre, $format est un tableau contenant la "personalisation", c'est a dire des paramètres pris en compte par sprintf().
Il y en a 5 au total :

  • Le 1er correspond au formatage d'une variable simple.
  • Le 2ème correspond au formatage d'un début de "container", c'est à dire d'un tableau ou d'un objet.
  • Le 3ème correspond à la fin d'un container
  • Le 4ème est le/les caractère d'indentation
  • Le 5ème sert à se repérer dans la fermeture d'une balise, il détermine en fait sur quoi on se base pour le balisage
    et stock la bonne valeur dans ce cas, la valeur peut être 'key', 'type', 'val' ou 'depth'.

sprintf() lui même peut prendre 4 paramètres :

  • Le 1er est le nom de variable : %1$s
  • Le 2eme est son type : %2$s
  • Le 3eme est sa valeur : %3$s
  • Le 4eme est la profondeur actuelle (cas de tableaux imbriqués) : %4$s

Le 3eme paramètre $prefix sert à régler un cas bien particulier :
un tableau indexé aura uniquement des chiffres comme clés, et si on veut utiliser la clé comme nom de balise en XML, un chiffre n'est pas valide.
On peut donc passer en argument une chaine qui servira de préfixe à toutes les clés commençant par un chiffre.

Grace à ceci, on peut personaliser une sortie allant du XML au CSV en passant par du HTML.
Le format par défaut étant XML.
function dumpFormat($struct, $format = false, $prefix = false)
{
   static $stack = array();
   static $depth = 0;
   static $str = '';
   
   if ($format === false) {
      $format = array (
         '<%2$s name="%1$s">%3$s</%2$s>'."\n",
         '<%2$s name="%1$s">'."\n",
         '</%2$s>'."\n",
         "\t",
         'type'
      );
   }
   
   if (is_object($struct)) $struct = get_object_vars($struct);
   
   foreach ($struct as $key => $val) {
      if ($prefix != false) {
         if (preg_match('(^\d)', $key)) $key = $prefix.$key;
      }
      $type = gettype($val);
      if (is_object($val)) {
         array_push ($stack, ${$format[4]});
         $str .= str_repeat($format[3], $depth).sprintf($format[1], $key, $type, $val, $depth);
         $depth++;
         dumpFormat(get_object_vars($val), $format, $prefix);
      }
      if (is_array($val)) {
         array_push ($stack, ${$format[4]});
         $str .= str_repeat($format[3], $depth).sprintf($format[1], $key, $type, $val, $depth);
         $depth++;
         dumpFormat($val, $format, $prefix);
      }
      elseif (is_scalar($val)) {
         $str .= str_repeat($format[3], $depth).sprintf($format[0], $key, $type, $val, $depth);
      }
   }
   
   $depth--;
   
   if ($depth != -1) {
      ${$format[4]} = array_pop($stack);
      $str .= str_repeat($format[3], $depth).sprintf($format[2], $key, $type, $val, $depth);
   }
   
   else {
      $stack = array();
      $depth = 0;
      $ret = $str;
      $str = '';
      return $ret;
   }
}
Exemple de personnalisation
// imaginons que $data est un tableau ou un objet

// format HTML en couleur, imitant var_dump().. En plus classe :)
$format = array (
   '&nbsp;&nbsp;&nbsp;&nbsp;<b><span style="color:#66B">%1$s</span>
   </b> => <i><span style="color:#6B6">(%2$s)</span></i> %3$s<br />', // Variable simple
   '<div style="border-left:3px solid #66B;margin-left:20px;margin-top:10px"><b>
   <span style="color:#66B;background-color:#DDD">&nbsp;%1$s&nbsp;</span>
   </b> => <b>{</b> <span style="color:#6B6">(%2$s)</span><br />', // Début de container
   '&nbsp;<b>}</b><span style="color:#66B">(%1$s)</span></div>', // Fin de container
   '', // Indentation
   'key' // repère de balisage
);

echo dumpFormat($data, $format);


// format XML utilisant les noms de variables pour le balisage
$format = array (
   '<%1$s class="%2$s">%3$s</%1$s>'."\n", // Variable simple
   '<%1$s class="%2$s">'."\n", // Début de container
   '</%1$s>'."\n", // Fin de container
   "\t", // Indentation
   'key' // repère de balisage
);

echo '<pre>';
// On préfixe les clés numériques par 'item'
echo htmlspecialchars(dumpFormat($data, $format, 'item'));
echo '</pre>';

Auteur : genova
Version : 16/01/2006
Un print_r() amélioré
Un print_r() permettant l'affichage de la structure d'un tableau, avec deux trois colorations sympas
pour visualiser directement les sous tableaux et les clefs.
function printr($array)
{
   static $indentation = '';
   static $array_key = '';
   $cst_indentation = '&nbsp;&nbsp;&nbsp;&nbsp;';

   echo $indentation . $array_key . '<b>array(</b><br />';
   reset($array);
   while (list($k, $v) = each($array))
   {
      if (is_array($v))
      {
         $indentation .= $cst_indentation;
         $array_key = '\'<i style="color: #334499 ;">' . addslashes(htmlspecialchars($k)) . '</i>\' => ';
         printr($v);
         $indentation = substr($indentation, 0, strlen($indentation) - strlen($cst_indentation));
      }
      else
      {
         echo $indentation . $cst_indentation . '\'<i style="color: #334499 ;">' . 
 addslashes(htmlspecialchars($k)) . '</i>\' => \'' . addslashes(htmlspecialchars($v)) . '\',<br />';
      }
   }
   echo $indentation . '<b>)</b>' . (($indentation === '') ? ';' : ',') . '<br />';
}

rechercher
precedent    sommaire    suivant    telecharger

Valid XHTML 1.1!Valid CSS!

Les sources présentées sur cette page sont libres de droits et vous pouvez les utiliser à votre convenance. Par contre, la page de présentation constitue une œuvre intellectuelle protégée par les droits d'auteur. Copyright © 2006 Developpez Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site ni de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon vous encourez selon la loi jusqu'à trois ans de prison et jusqu'à 300 000 € de dommages et intérêts.