Render HTML using PHP

1

This question is very large and can be answered with multiple answers but I did not get answers in the discussion forum. Well I would like to know how to build the following page using PHP (but I built using html):

IthasthefollowingHTMLcode:

<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Titulo</title>

    <script type="text/javascript" src="../Bootstrap/js/jquery-1.11.1.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><scripttype="text/javascript" src="../Bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../datepicker/js/bootstrap-datepicker.js"></script>
    <script type="text/javascript" src="../Jquery-Validate/jquery.validate.min.js"></script>
    <script type="text/javascript" src="../Javascript/ActionsJS.js"></script>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" href="../Bootstrap/css/bootstrap.min.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="../datepicker/css/datepicker.css" media="screen" />

    <link rel="stylesheet" type="text/css" href="../CSS/StyleSheet.css"/>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
    <nav class="navbar navbar-default navbar-fixed-top" role="navigation"><!--------- START Navbar --------->
        <div class="container">
            <div class="navbar-header"><!-- START Brand and toggle get grouped for better mobile display -->
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> 
                    <span class="sr-only">Toggle navigation</span> 
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button> 
                <a class="navbar-brand" href="#">Meu Site</a>
            </div><!-- END Brand and toggle get grouped for better mobile display -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><!-- START Collect the nav links, forms, and other content for toggling -->
                <ul class="nav navbar-nav navbar-right">
                    <li><button type="button" class="btn btn-info navbar-btn" data-toggle="modal" data-target="#login_modal">Login</button></li>
                    <li><button type="button" class="btn btn-info navbar-btn" data-toggle="modal" data-target="#create_account_modal">Create Account</button></li>
                </ul>
                <form class="navbar-form span7 text-center" role="search" id="search-form" action="../action.php" method="get">
                    <div class="input-group">
                        <input class="form-control" type="text" id="search_input" name="search_input" placeholder="Search" />
                        <div class="input-group-btn">
                            <button class="btn btn-default" type="submit" name="search_form_submit" value="search">Search</button>
                        </div>
                    </div>
                </form>
            </div><!-- END Collect the nav links, forms, and other content for toggling -->
        </div>
    </nav><!--------- END Navbar --------->

    <div class="wrapper" role="main"><!-- START Content -->
        <div class="container"><!-- START Related Tags -->
            <div class="row">
                <div id="right_sidebar" class="col-md-2 pull-right"><!-- START Right Sidebar -->
                    <div class="row">
                        <h4>Duraçao</h4>
                        <div class="radio">
                            <label><input type="radio" name="duratrion" value="dur-0" checked="checked">Indeterminado</label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="duratrion" value="dur-1">1 Dia</label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="duratrion" value="dur-2">3 Dias</label>
                        </div>
                        <div class="radio">
                            <label><input type="radio" name="duratrion" value="dur-3">5 Dias</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

So that I can exchange this small elements among others pages (.php) see my rudimentary example: I created this header.php file (which renders navbar in red)

<?php
echo'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Titulo</title>

        <script type="text/javascript" src="../Bootstrap/js/jquery-1.11.1.min.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><scripttype="text/javascript" src="../Bootstrap/js/bootstrap.min.js"></script>
        <script type="text/javascript" src="../datepicker/js/bootstrap-datepicker.js"></script>
        <script type="text/javascript" src="../Jquery-Validate/jquery.validate.min.js"></script>
        <script type="text/javascript" src="../Javascript/ActionsJS.js"></script>

        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
        <link rel="stylesheet" type="text/css" href="../Bootstrap/css/bootstrap.min.css" media="screen" />
        <link rel="stylesheet" type="text/css" href="../datepicker/css/datepicker.css" media="screen" />

        <link rel="stylesheet" type="text/css" href="../CSS/StyleSheet.css"/>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    </head>
    <body>
        <nav class="navbar navbar-default navbar-fixed-top" role="navigation"><!--------- START Navbar --------->
            <div class="container">
                <div class="navbar-header"><!-- START Brand and toggle get grouped for better mobile display -->
                    <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> 
                        <span class="sr-only">Toggle navigation</span> 
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button> 
                    <a class="navbar-brand" href="#">Meu Site</a>
                </div><!-- END Brand and toggle get grouped for better mobile display -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"><!-- START Collect the nav links, forms, and other content for toggling -->
                    <ul class="nav navbar-nav navbar-right">
                        <li><button type="button" class="btn btn-info navbar-btn" data-toggle="modal" data-target="#login_modal">Login</button></li>
                        <li><button type="button" class="btn btn-info navbar-btn" data-toggle="modal" data-target="#create_account_modal">Create Account</button></li>
                    </ul>
                    <form class="navbar-form span7 text-center" role="search" id="search-form" action="../action.php" method="get">
                        <div class="input-group">
                            <input class="form-control" type="text" id="search_input" name="search_input" placeholder="Search" />
                            <div class="input-group-btn">
                                <button class="btn btn-default" type="submit" name="search_form_submit" value="search">Search</button>
                            </div>
                        </div>
                    </form>
                </div><!-- END Collect the nav links, forms, and other content for toggling -->
            </div>
        </nav><!--------- END Navbar --------->
    </body>
</html>
';
?>

I think this is not the best way and I would like to know what would be a suitable way, where I could call these small .php (containing the navbar "red" the sidebar in "green") and build a unique page still have other points that would be 1st the fact that I am replicating the tag in the pages header.php and sidebar.php how could I be more efficient in this? 2º the content of the tag is different between each page 3rd in case of user login how would I change the Login and Create account buttons in .php to a logout button?

    
asked by anonymous 08.01.2015 / 17:39

2 answers

7

The simplest way to do this is to separate the HTML into small blocks and place them in separate files. This will simplify the maintenance of the files and avoid the repetitions you commented on. In the end, just put the pieces together in another PHP file.

One way to get these pieces together is to use include . This allows you to include the contents of other files in the file you are calling.

Here is a working example:

index.php

<html>
  <head></head>
  <body>
    <div class="cabecalho">
      <?php include 'cabecalho.php'; ?>
    </div>
    <div class="barra_lateral">
      <?php include 'barra_lateral.php'; ?>
    </div>
    <h1>Página inicial</h1>
    <p>Esta é a primeira página.</p>
  </body>
</html>

cabecalho.php

<ul>
  <li><a href="/index.php">Página inicial</a></li>
  <li><a href="/contato.php">Contato</a></li>
</ul>

sidebar.php

<ol>
  <li>Este é o primeiro item</li>
  <li>Este é o segundo item</li>
</ol>

A more elegant way is to use a template language . Template languages allow you to create an output based on a template - an HTML file full of "gaps" to fill in - that you can add logic to control what will be displayed.

If you want to go this route, I'd like you to take a look at Smarty and Twig .

And as commented by @GuilhermeNascimento and @WallaceMaxters, a great way to solve this and several other problems you will face is using MVC, some well-known frameworks implement this pattern as the Zend , CodeIgniter and CakePHP .

    
08.01.2015 / 18:50
2

@Ricardo, as answered our friend @Jonatas Oliveira, and answering your question in the comment, the solution placed is static . See the differences between:

include () require () include_once () require_once ()

ANTES DE TUDO SOBRE SUA PERGUNTA PRINCIPAL:

- You CAN create conditions inside a .php file that dynamically hide your html codes. A very basic example, without having to create includes, would be this:

    global $user;
    $user = $_SESSION['estouLogado'];
    if(isset($user) ){

echo '<div style="text-align: right;"><h4>Bem vindo, '.$user->get_user_name()."</h4>";
echo '</div>';
       }else{ ?>

        <!-- BOTÃO ENTRAR EM HTML--> 

    <?php } ?>

NOW ON THE FUNCTIONS:

include ();

PHP's include () function aims to include (as the name suggests) one file within the other when accessed. If there is any problem with its inclusion, a Warning will be displayed that the file could not be included and will continue to display the page normally without the file being included. The include () function accepts parameters via GET when calling a file. Check out the example below.

<?php
  //Exemplo de utilização da função include()
  include('./arquivo1.php?perfil=123'); //incluindo o arquivo1.php
  include('./lembrete.html'); //incluindo o arquivo lembrete.html
?>

In the example above, 2 files are included: file1.php and reminder.html. These files will be included without any problem since they are in the same path that was informed as a parameter in the use of the include () function;

require ();

PHP's require () function has the same functionality as include (), mentioned above, with the difference that if the file you are including does not exist (or is not found), a Fatal Error will be generated ( fatal error), paralyzing the execution of any script that comes after the require (); another divergence is the fact that this function does not accept parameters via GET for the called file. If you use this parameter, it will be ignored. Check out the example below:

<?php
  //Exemplo de utilização da função require()
  require('./arquivo1.php'); //incluindo o arquivo1.php
  require('./lembrete.html'); //incluindo o arquivo lembrete.html
?>

include_once (); and require_once ();

PHP's include_once () and require_once () functions have their functions "identical" to the include () and require () functions, respectively. I say "identical" (between quotation marks) because the only difference between them is that functions that have "_once" only allow the file to be added once on the page.

<?php
  //Exemplo de utilização da função include() e include_once()
  include('./arquivo1.php'); //incluindo o arquivo1.php
  include('./lembrete.html'); //incluindo o arquivo lembrete.html
  include_once('./arquivo1.php'); //tentando incluir o arquivo1.php novamente, ele não será incluso (caso o arquivo não exista, será apresentado um segundo warning)
?>

<?php
  //Exemplo de utilização da função require() e require_once()
  require('./arquivo1.php'); //incluindo o arquivo1.php
  require('./lembrete.html'); //incluindo o arquivo lembrete.html
  require_once('./arquivo1.php'); //tentando incluir o arquivo1.php novamente, ele não será incluso
?>
    
09.01.2015 / 15:14