zoukankan      html  css  js  c++  java
  • PHP 生成 Html

     1 <?php
     2 
     3 /**
     4 
     5 生成:<form id="form"><label><b>用户名:</b><input name="usrname"></label></form>
     6 
     7 $form = Html::tag('form')->attr(['id' => 'form']);
     8 $label = Html::tag('label');
     9 $b = Html::tag('b');
    10 $input = Html::tag('input')->attr('name', 'usrname');
    11 
    12 echo $form->add($label->add($b->add('用户名:'))->add($input))->make();
    13 
    14 */
    15 
    16 class Html{
    17 
    18     protected static $init = null;
    19     protected $attr = [];
    20     protected $tag = '';
    21     protected $elements = [];
    22     public $closings = ['br', 'hr', 'input', 'source', 'area', 'base', 'link', 'img', 'meta', 'basefont', 'param', 'col', 'frame', 'embed'];
    23 
    24     protected function __construct($tag){
    25 
    26         $this->tag = $tag;
    27     }
    28 
    29     public static function tag($value){
    30 
    31         return new static($value);
    32     }
    33 
    34     public function attr($name, $value = ''){
    35 
    36         if(is_array($name)){
    37             $this->attr = $name + $this->attr;
    38         }else{
    39             $this->attr[$name] = $value;
    40         }
    41 
    42         return $this;
    43     }
    44 
    45     public function add($element){
    46 
    47         $this->elements[] = $element;
    48         return $this;
    49     }
    50 
    51     public function make(){
    52 
    53         $attr = array_reduce(array_keys($this->attr), function($carry, $item){
    54             $carry .= ' ' .$item . '=' . '"'.$this->attr[$item] .'"' ;
    55             return $carry;
    56         });
    57 
    58         $html = '<'.$this->tag. $attr.'>';
    59         //遍历子元素调用 make 方法,形成递归
    60         foreach ($this->elements as $element){
    61 
    62             if(is_object($element)){
    63                 $element = $element->make();
    64             }
    65             $html .= $element;
    66         }
    67 
    68         if(!in_array($this->tag, $this->closings)) $html .= '</'.$this->tag.'>';
    69 
    70         return  $html;
    71 
    72     }
    73 
    74 
    75 }
  • 相关阅读:
    mysql explain语句各项含义
    group_concat用法以及字符串太长显示不全
    合并两个word文档,保持样式不变
    读取word模板,填充数据后导出
    java获取配置文件信息
    mysql5.6免安装使用
    时间格式转换
    Mysql中(@i:=@i+1)的作用
    SVN服务器搭建和使用(一)
    按需讲解之Supervisor
  • 原文地址:https://www.cnblogs.com/zbseoag/p/12717290.html
Copyright © 2011-2022 走看看