Home > OS >  PHP Echo Text into an existing word template
PHP Echo Text into an existing word template

Time:06-02

I'm trying to use PHP to populate data from MYSQL data to an existing Word template with our company's letterhead in it.

When i use the code as below on a blank word document, it works. BUT when i use it on my existing Word template document, it won't echo any text at all!

I've been searching for solutions, but not avail. Please help!

<html>
<head>
<style> 
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}

div {
font-family: myFirstFont;
}

</style>
</head>
<body>

<?php 

if(isset($_POST['NT2a'])){

ob_end_clean();
header("Content-type: application/vnd.openxmlformats-
officedocument.wordprocessingml.document");
header("Content-Disposition: attachment;Filename=test.doc");
header("Pragma: no-cache");
header("Expires: 0");

echo readfile("test.doc");
       
       echo "<div class='font'>";
       echo "Name :";
       echo $_POST["name"];
       echo "<br>";
       echo "<u>". 'Email :' ."</u>";
       echo $_POST["email"];
       echo "</div>";
      
}

?>  

CodePudding user response:

if it's working from a blank .word file, just put the content of the template inside your code : in other words for every line of your DB, you'll create a new word document with the content you need

CodePudding user response:

You can try and work with placeholders in the Word template. That is, you place something like %name% in the Word text, and replace the %name% by whatever name you would like to have in the Word file.

Before doing that, you will have to unzip the DOCX file, using the ZIP-extension in PHP. This will give you access to the files actually hidden in the DOCX file. Find the file with the placeholder, edit the content via PHP (make sure to mask XML entities), put it back into the ZIP, re-zip, and store the file as DOCX.

When i use the code as below on a blank word document, it works. BUT when i use it on my existing Word template document, it won't echo any text at all!

It works on a blank file, because Word will open the file, see that it's no DOCX but HTML, and open it as HTML file. When you simply add content to a DOCX file, you simply add something behind the end of the ZIP file, which in the best case is ignored.

  • Related