我正在寻找使用 PHP 构建 HTML 表单,但我想知道可能库已经存在。你知道我可以使用什么开源库吗?
您认为使用 php 创建函数来构造 HTML 表单是个好主意吗?性能(加载我网站的页面)有任何风险吗?
function input($label,$id,$type)
{
echo $label.' <input type="'.$type.'" id="'.$id.'" name="'.$id.'" />';
}
input('User name','login','text');
我的目的是建立一个库来快速维护代码。
最佳答案
我有几个我以前创建的函数。我将它们用于不依赖于框架的项目。现在,如果可能的话,我更喜欢使用 Symfony 的 Form 组件。
看一下,它会给你一个想法。
function lb($text, $forid='', $style='', $attr='')
{
if($style!='')
$style='style="'.$style.'"';
if($forid!='')
$forid='for="'.$forid.'"';
return '<label '.$style.$forid.' '.$attr.'>'.$text.'</label>';
}
//generates input field, and populates inputs. Good for edit forms too.
function in($name, $cust_val='', $style='', $attr='', $set_id=true)
{
global $edit;
$val='';
if(isset($edit[$name]))
$val=$edit[$name];
if($cust_val!='')
{
$val=$cust_val;
}
if($style!='')
$style='style="'.$style.'"';
$setid='';
if($set_id)
$setid="id=\"".$name."\"";
return '<input type="text" name="'.$name.'" '.$setid.' '.$attr.' '.$style.' value="'.ht($val).'">';
}
/*
* Prints multiple <td></td> for a table structure
*
* @param array vals - values to be used inside tds
* @param boolean encloseInTR when true puts <tr> outside tds
*/
function tds($vals, $encloseInTR=false)
{
$out='';
foreach($vals as $v)
{
$out.='<td>'.$v.'</td>';
}
if($encloseInTR)
$out = '<tr>'.$out.'</tr>';
return $out;
}
/*
* Prints multiple <th></th> for a table structure
*
* @param array vals - values to be used inside ths
* @param boolean $encloseInTHEAD when true puts <thead> outside th
* @param class class var to be added to th
*/
function ths($vals, $encloseInTHEAD=false, $class='')
{
$out='';
foreach($vals as $v)
{
if($class!='')
$out.='<th class="'.$class.'">'.$v.'</th>';
else
$out.='<th>'.$v.'</th>';
}
if($encloseInTHEAD)
$out = '<thead>'.$out.'</thead>';
return $out;
}
//alias htmlspecialchars
function ht($string)
{
return htmlspecialchars($string,ENT_QUOTES);
}
这就是我的表单代码的样子:
$form =
form_start(..)
.lb('First name','')
.in('name','','width:400px;')
.lb('Telefon','').cl()
.in('tel','','width:400px;')
//...
.form_end()
;
关于php - 使用 PHP 构建 HTML 表单的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057238/