code_junkie

Create Word Document using PHP in Linux

Nov 11th, 2011
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. header("Content-type: application/vnd.ms-word");
  2. header("Content-Disposition: attachment;Filename=document_name.doc");
  3.  
  4. echo "<html>";
  5. echo "<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">";
  6. echo "<body>";
  7. echo "<b>My first document</b>";
  8. echo "</body>";
  9. echo "</html>";
  10.  
  11. <?php
  12. function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
  13. {
  14. $word = new COM("word.application") or die("Unable to instantiate Word");
  15. //bring it to front
  16. $word->Visible = 1;
  17. //open an empty document
  18. $word->Documents->Add();
  19. //do some weird stuff
  20. $word->Selection->TypeText($sFileContent);
  21. $word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
  22. //closing word
  23. $word->Quit();
  24. //free the object
  25. $word = null;
  26. return $sFileName;
  27. }
  28. ?>
  29.  
  30.  
  31.  
  32. <?php
  33. $PATH_ROOT=dirname(__FILE__);
  34. $Return ="<table>";
  35. $Return .="<tr><td>Row[0]</td></tr>";
  36. $Return .="<tr><td>Row[1]</td></tr>";
  37. $sReturn .="</table>";
  38. fWriteFile("test",$Return,$PATH_ROOT);
  39. ?>
  40.  
  41. function mailMerge($templateFile, $newFile, $row)
  42. {
  43. if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template
  44. return false; // could not duplicate template
  45. $zip = new ZipArchive();
  46. if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
  47. return false; // probably not a docx file
  48. $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';
  49. $data = $zip->getFromName($file);
  50. foreach ($row as $key => $value)
  51. $data = str_replace($key, $value, $data);
  52. $zip->deleteName($file);
  53. $zip->addFromString($file, $data);
  54. $zip->close();
  55. return true;
  56. }
  57.  
  58. $replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');
  59. $newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');
  60. $templateName = 'personinfo.docx';
  61. if (mailMerge($templateName, $newFile, $replacements))
  62. {
  63. header('Content-type: application/msword');
  64. header('Content-Disposition: attachment; filename=' . $templateName);
  65. header('Accept-Ranges: bytes');
  66. header('Content-Length: '. filesize($file));
  67. readfile($newFile);
  68. unlink($newFile);
  69. }
  70.  
  71. echo "<meta http-equiv="Content-Type" content="text/html; charset=utf-8">";
Add Comment
Please, Sign In to add comment