php - 如何在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 文件保存在同一文件夹中,但我想要一个下载链接
解决方案
推荐阅读
- sql - Microsoft Access:为每个公司选择一个电子邮件地址
- directions - Azure Maps Directions Service 对自行车的错误请求
- javascript - 从 URL 保存 HTML 数据
- api - ActiveCollab API 返回所有活动项目
- jquery - 在不同的 DIV 上单击超链接时添加一个类
- symfony - Symfony - 如何在一个子域(不是全部)上动态记录用户
- android - 来自 macOS 应用程序的带有特殊字符的 ADB 命令
- javascript - 如何清除 redux-form 的 initialValues 中的一个值?
- list - 使用 elm 中的新数据更新嵌套记录
- java - 加载更多数据时停止 Recyclerview 的动画