php - 使用 PHP 构建 HTML 表单的库

标签 php html templates

我正在寻找使用 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/

相关文章:

Perl:安全的模板语言

c++ - 函数返回类型中的 g++ auto 和 typename 关键字

c++ - 从类对象访问模板参数

php - MySQL PHP : How to join same table multiple times?

html - 如何禁用 Google 幻灯片演示文稿 IFrame 导航

php - 将嵌套文本转换为字符串

html - 在固定位置写入文本的问题

Javascript 将 div 从屏幕左侧滑出

php - jQuery 将复选框值设置为 URL 并获取 PHP 中的值作为数组并使用 NOT IN 查询它

php - MySQL 半正矢公式中的语法错误