我正在创建一个WordPress插件,当按下按钮时会生成HTML页面。这样可行;虽然代码是在WP插件中,但问题与WordPress无关。下一步是向用户提示下载/打开已创建的文件。
根据此处和其他地方的研究,此过程应创建下载/打开提示:
/* another process creates an HTML file "somefile.html", and stores it
in the plugin folder; that is done with an fopen/fwrite/fclose.
This process is started by a button on the plugin settings page.
When the button is clicked, the "somefile.html" is created.
So at this point, the HTML file is created and stored in the plugin folder */
$size = filesize($thefile);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='somefile.html');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
exit;
该过程(通过按钮点击插件设置页面启动)确实创建了HTML文件,并且它正确存储在插件文件夹中(文件位置不是问题,将在最终版本中解决)。然后我看到打开/保存文件对话框。
如果我从服务器打开生成的HTML文件,HTML就是预期的。但是如果我通过打开/保存提示打开生成的文件,我会得到插件设置页面的表示,而不是生成的HTML。
我怀疑我需要一个obflush()/ flush(),但是在标题行之前放置这些语句并不能解决问题。
所以我的问题是open / save as对话框没有读取存储在服务器上的'somefile.html'。我得到一个带有打开对话框的插件设置HTML页面。
如何确保通过打开/保存对话框打开我创建的HTML文件?
(请注意,虽然代码在WordPress插件中,但问题并不是特定于WordPress。代码只是创建一个表单按钮;在提交时,表单操作会创建一个HTML文件并将其保存到服务器。然后使用'语句创建保存/打开对话框。)
ADDED
此代码应显示该过程。这是用于创建somefile.html文件的“有效”HTML页面。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>
This is the page with some content. It will create the HTML page (the 'xoutput' content).
</body>
<!--- the above is the page that is initially displayed -->
<?php
// now we create the content of the generated/saved file
$xoutput = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
<body>';
$xoutput .= 'There is some content generated here. Actual content doesn't matter.';
$xoutput .= '</body> </html>';
$thefile = "outputfile.html";
$handle = fopen($thefile, "w");
fwrite($handle, $xoutput);
fclose($handle);
$quoted = sprintf('"%s"', addcslashes(basename($thefile), '"\\'));
$size = filesize($thefile);
// now that the somefile.html has been created and stored, let's create the open/save dialog
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
exit;
return;
当您加载页面时,您会看到“此处生成一些内容”HTML页面,而不是“somefile.html”内容。
答案 0 :(得分:1)
新尝试和测试:
catch