lunes, 17 de junio de 2013

Imprimir variables en un documento en PHP

Este proceso sirve para imprimir variables en un archivo .doc o .rtf


comencemos 
lo primero que tenemos que hacer es diseñar una plantilla en un archivo .RTF 

ojo mis variables para este ejemplo serán 

1- codigoproyecto
2- nombredelproyecto
3- Investigadorprincipal
4- fechaemisioncarta

ahora lo importante código php 

$texto = file("files/documento.rtf");  //la ruta de nuestra plantilla , la que contiene nuestras variables
$tam = sizeof($texto);

for($i=0;$i<=$tam;$i++){
$todo = $todo.$texto[$i];
}
     
$todo=str_replace("codigoproyecto",$codigoproyecto,$todo); //remplazamos nuestra variable del archivo rtf por una variable php
$todo=str_replace("nombredelproyecto",$nombrepryecto,$todo);
$todo=str_replace("Investigadorprincipal",$investigador,$todo);
$todo=str_replace("fechaemisioncarta",date("H:i:s d/m/Y"),$todo);
     
$fp=fopen("files/prueba.rtf","w"); //ojo con la ruta del ducumento, tu ruta puede ser distinta
fwrite($fp,$todo);
fclose($fp);
ahora como descargamos el archivo generado (esto me costo mucho jejejej :D )
$file = "../files/prueba.rtf";
     
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=carta.doc');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

No hay comentarios:

Publicar un comentario