2014-09-19 28 views
0

我有一種方法用於從屬性數組中生成用戶表單。從函數驅動的html中製作格式正確的源代碼

該函數適用於我需要的功能,但是在查看源代碼時,它是一個連續的行,而不是更具可讀性的縮進格式。

這裏是產生源代碼:

<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' 
); 
+0

fyi:輸入標籤是自閉標籤,無論如何,你有一個'$ formElements'的示例數組值嗎? – Ghost 2014-09-19 22:48:18

+0

添加到問題 – datavoredan 2014-09-19 22:51:33

回答

1

你只需要添加相應的縮進和換行符在你的代碼是這樣的:在您的迴音statments

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>"; 
} 
0

利用\t\n ...玩弄它,你會得到你需要的東西:)