首页 > 解决方案 > 如何在php中添加.docx的下载链接

问题描述

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

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

我想用用户在表单中输入的值替换 {{Name}}、{{last name}} 和 {{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 文件保存在同一文件夹中,但我想要一个下载链接

标签: phpdownloadms-word

解决方案


推荐阅读