2016-09-19 182 views
-1

我構建了一個基於瀏覽器的小型帆布遊戲。我很好,Javascript和jQuery,但我只有平庸的經驗與PHP和特別是創建基於PHP的網頁。使用PHP創建HTML頁面

目前我在做的是檢查$_GET來檢索一些數據庫數據。 根據這些數據,我想創建「獨特的」HTML頁面。

例如:我有一個頁面叫做createGame.php,它檢查玩家是否在遊戲中。

如果他是,我想填充和顯示一個表。

我的PHP:

<?php 
    $gamedata = someObject // basicly the entire gamedata, playerIds, subObjects, a bunch of database data clumped together. 

    if ($gamedata ->playerHasJoined()){ 
     $table = // code here to create a unique table element 
    } 
    ?> 

    <body> 
    <div> 
     <?php echo $table ?> 
    </div> 
    </body> 

現在,基本上我的問題是:我該怎麼辦 「最好」 的建立表格元素? 辦:

$table = "<table>"; 
$table .= "<tr><th>Im the Header</th></tr>"; 
$table .= "do this 50 times more"; 

還是有更好的方法來創建基於我$gamedata變量的元素? 或者我應該用另一種方式來構建我的HTML頁面嗎?

謝謝

+0

可能會告訴我們'$ gamedata'中的內容是什麼,所以我們對你正在處理的數據有一些想法 – RiggsFolly

+0

看看這些答案http://programmers.stackexchange.com/questions/159529/how- to-structure-template-system-using-plain-php –

+1

你的問題相當廣泛,可能是基於觀點的。但是,對於我的*「2美分」*;你可以使用包含HTML標記,只需使用變量插入他們應該顯示的位置。然而,你的「做這50倍」*尚不清楚應該保持什麼。你可以使用一個'foreach',可能,如果這應該保存db列的數據。 –

回答

1

現在好像你要創建之初的所有HTML右側,然後只打印整個頁面。我會做的是建立所有樣板(無論響應中的內容都保持相同的代碼),然後在整個頁面中回顯內容。

例子:

<body> 
    <?php 
     $array = ['One', 'Two', 'Three']; 
    ?> 
    <ul> 
     <?php 
      foreach($array as $item) { 
       echo "<li>" . $item . "</li>"; 
      } 
     ?> 
    </ul> 
</body> 

如果你正在做一些更復雜的,我會建議你使用模板引擎就像嫩枝(http://twig.sensiolabs.org/),使生活更方便自己。

1

你可以不喜歡它

<table> 
    <tr> 
     <?php 
     $header = array_keys($_GET); 
     for ($x=0; $x<count($header); $x++) { 
     ?> 

     <th><?=$header[$x]?></th> 

     <?php 
     } 
     ?> 
    </tr> 
    </table> 
1

也許,最好的辦法是使用模板引擎,如Smarty,或Twig

這裏是它是如何與枝條做:

require_once '/path/to/vendor/autoload.php'; 

$loader = new Twig_Loader_Filesystem('/path/to/templates'); 
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache', 
)); 

$rows = fetch_an_array_from_database(); 

echo $twig->render('index.html', [ 'table_rows' => $rows ]); 

其中'/path/to/vendor/autoload.php'Composer生成的文件。

index.html

<table> 
{% for row in table_rows %} 
<tr> 
    <td>Name</td><td>{{ row.name }}</td> 
    <td>Age</td><td>{{ row.age }}</td> 
    <!-- etc. --> 
</tr> 
{% endfor %} 
</table>