Advertisement
PifyZ

Classe PHP utile pour générer facilement du code HTML

Feb 19th, 2012
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.76 KB | None | 0 0
  1. class Html {
  2.     /**
  3.      * Permet de générer facilement de l'HTML
  4.      *
  5.      * @author  PifyZ
  6.      * @version 1.0 19/02/2012
  7.     **/
  8.  
  9.     private $html = '';
  10.     private $inline = array('br', 'hr', 'img', 'input'); /* Ils ne sont pas tout listés (à changer au besoin) */
  11.     private $balisesOuverte = array();
  12.  
  13.     public function __construct() {
  14.         /* Vide */
  15.     }
  16.  
  17.     public function __call($balise, $attributs) {
  18.         $attributs = implode('|', $attributs);
  19.         $attributs = explode('|', $attributs);
  20.  
  21.         $return = '<' . $balise;
  22.  
  23.         foreach ($attributs AS $attribut) :
  24.             $pregMatch1 = '#(.[^:]+):(.+)#';
  25.             $pregReplace1 = ' $1="$2"';
  26.  
  27.             $pregMatch2 = '#texte:(.+)#';
  28.             $pregReplace2 = '$1';
  29.  
  30.  
  31.             if (preg_match($pregMatch1, $attribut) AND !preg_match($pregMatch2, $attribut)) :
  32.                 $return .= preg_replace($pregMatch1, $pregReplace1, $attribut);
  33.             endif;
  34.  
  35.             $texte = (preg_match($pregMatch2, $attribut)) ? preg_replace($pregMatch2, $pregReplace2, $attribut) : '';
  36.         endforeach;
  37.  
  38.         if (in_array($balise, $this->inline)) :
  39.             $return .= ' />';
  40.         else :
  41.             $this->balisesOuverte[] = $balise;
  42.             $return .= '>' . $texte;
  43.         endif;
  44.  
  45.         $this->html .= $return;
  46.  
  47.         return $this;
  48.     }
  49.  
  50.     public function texte($texte) {
  51.         $this->html .= $texte;
  52.  
  53.         return $this;
  54.     }
  55.  
  56.     public function fin() {
  57.         $this->html .= '</' . array_pop($this->balisesOuverte) . '>';
  58.  
  59.         return $this;
  60.     }
  61.  
  62.     public function __toString() {
  63.         return $this->html;
  64.     }
  65. }
  66.  
  67. /* Exemple d'utilisation (non testé) ->
  68.     $html = new Html();
  69.     $html->h1('texte:Titre de taille 1')->fin()
  70.         ->p('texte:Texte')->fin();
  71.     echo $html;
  72.  
  73.    Ou encore (génère le même code) (non testé) ->
  74.     $html = new Html();
  75.     $html->h1()
  76.         ->texte('Titre de taille 1')
  77.     ->fin()
  78.     ->p()
  79.         ->texte('Texte')
  80.     ->fin();
  81.     echo $html;
  82. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement