Render HTML using PHP

Asked

Viewed 2,487 times

1

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

inserir a descrição da imagem aqui

it has the following HTML code:

<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>
    <script type="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 these 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>
        <script type="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 little ones. php (containing the navbar "red" the sidebar in "green") and build a single page still have other points that would be 1º the fact that I’m replicating the tag in the pages header.php and sidebar.php how could I be more efficient in this appecto? 2º the content of the tag is different between each page 3º in case of user login how would change the Login and Create Account buttons in . php to a logout button?

  • you put "render html with php", but this is not the problem, because in a way they are linked and who renders is the client-side, could explain what the goal, preferably write for "topics" (more organized), thanks.

  • @Guilhermenascimento the goal is to break the HTML (which generates the image) into small codes phps. so that it is possible to mount a code . php that imports for example a.php sidebar.php header, .php form and create a single page with these parts

  • 2

    you made that clear in the commentary, but I had not understood it in the question, for the title leads to understand something else. Writing by topics helps :) But I did understand what you need, in my opinion it is something that can actually get several different answers, but it is not an invalid question. As for your code me personally (my opinion only) I think that if it’s about organization, you should seriously think about a system of Template and maybe a MVC.

  • posted an example in . php where the header is generated by arquvio . php as I would to "link" this header to a file . php that generates the footer for example?

2 answers

7


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

One of the ways for you to put these pieces together is by using include. This allows you to include the content of other files in the file you are calling.

Follow a functional 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>

header.php

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

barra_lateral.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 a template-based output - an HTML file filled with "gaps" to fill in - that you can add logic to control what will be displayed.

If you want to go down this path I suggest you look at the Smarty and the Twig.

And as commented by @Guilhermenascimento and @Wallacemaxters, a great way to solve this and several other problems you’ll face is by using MVC, some well-known frameworks implement this standard as the Zend, the Codeigniter and the Cakephp.

  • but in this solution is dynamic? because there will be a registration and login of users and there are areas where will only be allowed to view members

  • 1

    An MVC would also be fine :)

  • @Wallacemaxters huahuahua was the same that I commented on the question, a MVC + template, would be the best way :) +1 ae for you

  • @Ricardohenrique the dynamic part will have to be done inside each file checking whether the user is logged in or not. By your question I had understood only that you wanted to know how it would be possible to organize the files.

  • @Guilhermenascimento, I edited my reply to include the MVC, thank you for the comment.

  • @Wallacemaxters, I edited my reply to include the MVC, thank you for the comment

  • Just a hint, parentheses in include() is not necessary, prefer include '...';

  • @Guilhermenascimento, great tip. You have a legal explanation here: http://stackoverflow.com/a/21572779/845307 - TL;DR: O include is not a function so there is no need for parentheses.

  • Exactly @Jonatasoliveira

Show 4 more comments

2

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

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

ANTES DE TUDO SOBRE SUA PERGUNTA PRINCIPAL:

- You CAN create conditions within a.php file that dynamically hide your html code. A very basic example, without needing 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 ABOUT THE DUTIES:

include();

The PHP include() function aims to include (as the name suggests) one file within the other when accessed. If any problem occurs in the inclusion of this one, a Warning (warning) will be displayed that could not include the file and will continue the display of the page normally without the inclusion of the file. 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 above example, 2 files are being included: arquivo1.php and reminder.html. These files will be included without any problem as long as they are in the same path that was entered as parameter in the use of include function();


require();

The PHP require() function has the same functionality as the include() function mentioned above, except that if the file you are including does not exist (or is not found), a Fatal Error (fatal error) will be generated, paralyzing the execution of any script that comes after the require() line; 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 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();

The include_once() and require_once() functions of PHP have their functionality "identical" to include() and require() functions, respectively. I say "identical" (in quotes) because the only difference between them is that the functions that have "_Once" only allow the inclusion of the file 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
?>
  • ,@Rafael would like to divide the same page (image) into components, 3 components (the header in red, the buttons in green and the side in blue) each component in a file . php and would like to assemble the 3 components through a Fourth file. php, how could I do that? so that I could be reusing these components, however there are some restrictions the content of the <head> varies from page to page. remembering that you should not (as well as css inside html) have code . php inside code . html

  • @Ricardohenrique, HTML is a markup language. It is not a language in which you can create logics and determine actions, by the way, it IS NOT A PROGRAMMING LANGUAGE. I don’t understand what your difficulty is in doing includes. I think you should study more PHP. One day you will. Hug.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.