如何在php中添加.docx的下载链接

时间:2019-04-15 19:38:34

标签: php download ms-word

我想在输入和提交值时在表单上添加一个下载链接,然后应该创建一个链接来下载.docx文件。

我以前使用过取消链接功能。在本地主机上运行正常,但在实时服务器上,它在带有不可读符号的窗体下方显示.docx文件。

我想用用户在表单中输入的值替换{{Name}},{{lastname}}和{{previews name}}。然后创建一个下载链接,该链接将下载具有用户输入的特定值的.docx文件。同样,如果用户要编写预览名称,它将显示在文件中: (出生:预览姓名)

如果用户未填写预览名称-它只会显示名字和姓氏。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Employee Details</title>
  </head>
  <body>
    <form method="post" action="#">
      <input placeholder="First Name" type="text" name="firstname" />
      <input placeholder="Last Name" type="text" name="lastname" />
      <input placeholder="Previews Name" type="text" name="prevname" />
      <input type="submit" name="submit" />
    </form>
  </body>
  <?php
    if(isset($_POST["submit"])) {
        $fname = (string)$_POST["firstname"];
        $lname = (string)$_POST["lastname"];
        $prevname = (string)$_POST["prevname"];

        $source = 'template.docx';
        $full_path = $fname.'output.docx';
        $file = $full_path;
        //Copy the Template file to the Result Directory
        copy($source, $full_path);

        // add calss Zip Archive
        $zip_val = new ZipArchive;

        //Docx file is nothing but a zip file. Open this Zip File
        if($zip_val->open($full_path) == true)
        {
            // In the Open XML Wordprocessing format content is stored.
            // In the document.xml file located in the word directory.

            $key_file_name = 'word/document.xml';
            $message = $zip_val->getFromName($key_file_name);

            // this data Replace the placeholders with actual values
            $message = str_replace("{{Name}}", $fname, $message);
            $message = str_replace("{{last name}}", $lname, $message);
            $message = str_replace("{{previews name}}", '(born:'.$prevname.')', $message);


            //Replace the content with the new content created above.
            $zip_val->addFromString($key_file_name, $message);
            $zip_val->close();


            header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            header("Content-Disposition: attachment; filename=".$file);
            readfile($file);
            unlink($file);
            exit();

        }
    }
  ?>
</html>

此代码将.docx文件保存在同一文件夹中,但我想要一个下载链接

0 个答案:

没有答案