What are the ways to create html file using php?

3

I wanted to know what possibilities I have to create a arquivo.html using php .

In case I wanted to make a button clicked, I would generate this for myself.

For example, I have a page in php and it has a button in it. Clicking this button would run the code that would create this arquivo.html for me in a given directory. Then it would be possible to access this arquivo.html via url .

What functions in php do I need to use to create such a file? And if I want to change it later, how?

    
asked by anonymous 17.02.2017 / 19:25

1 answer

7

One of the quick ways to take advantage of an existing PHP is this:

<?php
   ob_start();                  // Isto bloqueia a saida do PHP para a "tela"

   ... tudo que você faria normalmente no PHP


   $gerado = ob_get_contents(); // Aqui capturamos o que seria enviado
   ob_end_clean();              // E limpamos, pois já está na string

   // neste momento, tudo que seria enviado para o cliente está em $gerado
   // e pode ser salvo em disco

   file_put_contents('arquivo.html', $gerado);


If you're building a slightly more sophisticated application, you can avoid output buffer and generate HTML directly in string . Instead of using echo , for example, you can concatenate this way:

<?php
     $titulo   = 'Meu HTML gerado'; // normalmente vai pegar de DB ou formulario
     $conteudo = 'Lorem Ipsum Batatas Doces';

     // Montamos nosso HTML no PHP, da forma que quisermos
     // \t é o tab, \n a quebra de linha
     $html  = "<html>\n";
     $html .= "\t<head>\n";
     $html .= "\t\t<title>".htmlentities( $titulo )."</title>\n";
     $html .= "\t</head>\n";
     $html .= "\t<body>\n";
     $html .= "\t\t<div>".htmlentities( $conteudo )."</div>\n";
     $html .= "\t</body>\n";
     $html .= "</html>\n";

     //... e vai montando o arquivo com variáveis etc
     // e depois salva

     file_put_contents('arquivo.html', $html);         
    
17.02.2017 / 19:39