在项目的实际开发中,经常需要设计各种各样的表单。 直接创建HTML表单很简单,但修改和维护相对麻烦。 因此,可以利用PHP实现Web表单生成器,以定制具有不同功能的表单以满足特定需求。
具体需求如下
1 .使用多维数组保存有关表单的信息。
2 .支持的表单项有五种:文本框、文本字段、单框、复选框和下拉列表。
3 .保存每个表单项的标记、提示文本、属性、选项值、默认值等。
4 .将功能封装为函数,并基于传递的参数生成指定的表格。
一、首先,如图所示创建数组。
$date=[
[
' text'='姓名: ',
' tag'='input ',
' attr'=['type'='text ',' name'='username']
]、
[
“text'=“账号:”,
' tag'='input ',
' attr'=['type'='text ',' name'='username']
]、
[
' text'='密码: ',
' tag'='input ',
' attr'=['type'='password ',' name'='pwd']
]、
[
" text'="邮箱: ",
' tag'='input ',
' attr'=['type'='text ',' name'='email']
]、
[
' text'='电话: ',
' tag'='input ',
' attr'=['type'='text ',' name'='tel']
]、
[
' tag'='input ',
' text'='性别:',
' attr'=['type'='radio ',' name'='gender'],
' option'=['m'='男人',' w'='女人' ]
]、
[
' tag'='select ',
' text'='地址:',
' attr'=['name'='area'],
' option'=[
请选择“='--。
' BJ'='北京',
' SH'='上海',
' SZ'='深圳',
" CQ "="重庆",
' SC'='四川',
" HB "="河北",
" SD "="山东",
' LN'='辽宁',
" hlj "="黑龙江",
' JL'='吉林',
' GS'='甘肃',
' QH'='青海',
]
]、
[
' tag'='textarea ',
' text'='自我介绍:',
' attr'=['name'='declare ',' cols'='50 ',' rows'='5']
]
];
?
二、然后用include将该数组导入函数function.php,在function中创建函数。 如图所示:
include 'date.php ';
函数ge rence (
全球$ date;
$html=' ';
foreach($dateas$item ) {
if$item['tag']=='input'}{
生成输入标记函数
$html=$html.input_html($item );
}
elseif($item['tag']=='select ' ) {
//生成下拉列表的标签函数
$html=$html.select_html($item;
}
elseif($item['tag']=='textarea ' ) }
//生成多行文本
$ html=$ html.textarea _ html ($ item );
}
}
返回$ html;
}
函数输入_ html ($ item ) {
$html=' ';
if $ item [ ' attr ' ] [ ' type ' ]==' text ' } {
//生成文本框
$html=$item['text'].';
}
else if ($ item [ ' attr ' ] [ ' type ' ]==' radio ' ) }
//生成单选按钮
$html=$item['text'];
$ html=$ html.' { $ item [ ' option ' ] [ ' m ' ] };
$ html=$ html.' { $ item [ ' option ' ] [ ' w ' ] };
} else if ($ item [ ' attr ' ] [ ' type ' ]==' password ' ) }
$html=$item['text'].';
}
返回$ html.'
}
functionselect_html($item ) {
$html=' ';
$html=$item['text'];
$html.=';
foreach($item['option']as$v ) {
$html.='$v ';
}
$html.=';
返回$ html.'
}
函数textarea _ html ($ item ) {
$html=' ';
$html=$item['text'];
$html.=';
返回$ html;
}
三.最后在include中将此函数引入到输出index.php中。 如图所示:
include 'function.php ';
echo gerence (;
?
结果如下: