从功能驱动的html制作格式正确的源代码

时间:2014-09-19 22:45:32

标签: php html forms oop

我有一个方法,用于从属性数组生成用户表单。

该功能适用​​于我需要的功能,但是在查看源代码时,它是一个连续的行,而不是更易读的缩进格式。

以下是生成的源代码:

<form><input name=songName type=text placeholder=Title </input><input name=songArtist type=text placeholder=Artist </input><input name=songGenre type=text placeholder=Genre </input><input name=year type=number placeholder=Year </input></form>

以下是我想要的:

<form>
    <input name=songName type=text placeholder=Title </input>
    <input name=songArtist type=text placeholder=Artist </input>
    <input name=songGenre type=text placeholder=Genre </input>
    <input name=year type=number placeholder=Year </input>
</form>

这是生成html的最终函数:

public function formGenerate($formElements)
{
    echo "<form>";

    foreach($formElements as $name=>$properties)            
    {
        echo "<input "."name=".$name." ";

        $propertiesArray    = explode('|',$properties);

        foreach($propertiesArray as $property)              
        {
            $split          = $this->splitPropertyAndValue($property);
            $propertyName   = $split['property'];
            $propertyValue  = $split['value'];

            echo $propertyName.'='.$propertyValue." ";
        }
        echo "</input>";
    }
    echo "</form>";
}

以下是为$ formElements传递的数组示例:

$formElements = array
(
    'songName'      =>  'type:text|placeholder:Title',
    'songArtist'    =>  'type:text|placeholder:Artist',
    'songGenre'     =>  'type:text|placeholder:Genre',
    'year'          =>  'type:number|placeholder:Year'
);

2 个答案:

答案 0 :(得分:1)

您只需在代码中添加相应的缩进和换行符,如下所示:

public function formGenerate($formElements)
{
    echo "<form>\n";   // adding the \n for form

    foreach($formElements as $name=>$properties)            
    {
        echo "    <input "."name=".$name." ";

        $propertiesArray    = explode('|',$properties);

        foreach($propertiesArray as $property)              
        {
            $split          = $this->splitPropertyAndValue($property);
            $propertyName   = $split['property'];
            $propertyValue  = $split['value'];

            echo $propertyName.'='.$propertyValue." ";
        }
        echo ">\n"; // self closing tag!
    }
    echo "</form>";
}

答案 1 :(得分:0)

在你的echo语句中使用\t\n ...玩它并且你得到你需要的东西:)