Rodrigo Régis

Tag: doc

Exportar para word com PHP

by Rodrigo Régis Palmeira on jul.09, 2009, under PHP

Olá
No meu último post eu expliquei como exportar dados formatados em html para o excel.
Hoje vou explicar como exportar para word.
Na verdade, só vamos mudar a extensão do arquivo a ser exportado e o parâmetro application do header.

Vamos forçar o download do arquivo através da função header() que é nativa do PHP.

Coloquei a function como método estático (igual ao método toXLS) dentro de uma classe (Util.php) para que a coleção de funções de uso geral fiquem mais organizadas e acessíveis.

Segue o método (Util.php):

<?php
class Util
{
	/**
	 * @author Rodrigo Régis Palmeira
	 * @link http://www.rodrigoregis.com.br
	 * @param string $html
	 * @return file.doc
	 */
  public static function toDOC($html, $nome = 'file.doc', $destino = null)
  {
  	if (!$destino)
  	{
  		header("Content-type: application/vnd.ms-word");
  		header("Content-type: application/force-download");
  		header("Content-Disposition: attachment; filename=\"{$nome}\"");
  		header("Pragma: no-cache");
  		echo $html;
  		exit();
  	}
  	else
  	{
  		file_put_contents($destino.'/'.$nome, $html);
  		exit();
  	}
  }
}
?>

Vamos implementá-lo (relatorio.php):

<?php
require('Util.php');
$html = <<<HTML
<table width='90%' border='1'>
	<tr>
		<th>Título </th>
		<th>Título 2</th>
		<th>Título 3</th>
	</tr>
	<tr>
		<td>Dados 1</td>
		<td>Dados 2</td>
		<td>Dados 3</td>
	</tr>
	<tr>
		<td>Dados 4</td>
		<td>Dados 5</td>
		<td>Dados 6</td>
	</tr>
	<tr>
		<td>Dados 7</td>
		<td>Dados 8</td>
		<td>Dados 9</td>
	</tr>
</table>
HTML;

//Chamando o método
Util::toDOC($html);
?>

Por hoje é só!

Espero ter ajudado!

15 Comments :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

Archives

All entries, chronologically...