【发布时间】:2016-10-02 10:44:03
【问题描述】:
我目前正在开发一个项目,该项目使用 HTML 和 PHP 允许用户将信息输入 Web 表单以生成 Excel 文件。提交时,表单会运行 PHP 文件 main.php:
<?php
// output headers so that the file is downloaded rather than displayed
$order = $_POST["order"];
header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$_POST['order'].'.xls"');
exec('php xl.php');
sleep(2);
readfile('xl_template.xls');
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
其中“xl.php”是另一个 PHP 文件,“xl_template”是我希望修改的 Excel 工作表的模板。 main.php的目的是抓取修改后的模板下载到用户电脑,而xl.php实际上是修改了Excel模板保存到服务器电脑(使用PHPExcel库):
<?php
// this file will be called by main.php
// after execution, there should be a newfile.xls
// for the main.php to read from
error_reporting(E_ALL);
require('Classes/PHPExcel.php');
// variable definitions
$template = "xl_template.xls";
$objPHPExcel = PHPExcel_IOFactory::load($template);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->getCell('A2')->setValue('123400000000000000000001');
$objWorksheet->getCell('B2')->setValue('it worked!');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save($template);
?>
当从终端调用 xl.php 文件然后填写表单时,这将按预期工作。但是,当通过exec('php xl.php') 方法从main.php 调用xl.php 时,Excel 文件没有得到更新,我认为这意味着xl.php 没有成功执行。
除了exec(),我还尝试了system()、shell_exec、反引号运算符和passthru(),结果相同。另外,我尝试过 Javascript 和 JQuery 方法,使用 $.get('xl.php') 和 $.ajax({url: 'xl.php'}) 调用 xl.php 文件,但没有成功。
任何对此问题的见解将不胜感激,因为我仍然是使用 PHP 的新手。谢谢。
【问题讨论】:
-
这么多文字 - 你的问题是什么?你不能从 php 脚本调用 xl.php?
-
为什么要启动一个单独的 php 来执行该外部脚本?你不能把第二个脚本写成函数调用,然后简单地
include(),然后做run_excel_stuff()吗? -
@Xatenev:我可以调用它,但它不会修改我在服务器端拥有的 Excel 文件。
-
@MarcB:我也尝试了
include()方法,结果相同。我必须分离文件的原因是,如果 main.php 中的readfile()方法在它之前调用函数会导致错误。所以我需要在调用readfile()之前修改Excel文件。 -
系统调用可能被禁止。为什么
readfile在以前执行过一个函数时会导致错误?当您输出错误和警告消息而不是记录它们时,会出现文件格式错误。如果修改只是针对单个请求,则无需将内容存储到磁盘。
标签: javascript php jquery html excel