我正在使用PHPWord创建文档。我需要做的是编辑现有docx/odt文档的页眉/页脚内容。将内容添加到文档并不难。但我花了整整一天的时间在互联网上寻找解决方案。这里是通过我只能够将内容添加到现有的页眉/页脚内容的代码:如何使用PHPWord从文档中编辑页眉/页脚?
$source = "DumpFiles/".$_FILES['file']['name'];
$fileName = $_FILES['file']['name'];
$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
echo "File Loaded";
// Get Sections from the imported document...
$sections = $phpWord->getSections();
$section = $sections[0];
// Adding Header and Footer Content
if(isset($_POST['headerContent']) && $_POST['headerContent']!=null)
{
$headert = $section->createHeader();
$table = $headert->addTable();
$table->addRow();
$table->addCell(4500)->addText($_POST['headerContent']);
}
if(isset($_POST['footerContent']) && $_POST['footerContent'])
{
$footervar = $section->createFooter();
$table = $footervar->addTable();
$table->addRow();
$table->addCell(4500)->addText($_POST['footerContent']);
}
我明白global
变量的使用直接是不好的做法。 :-p
我会改正我的代码中的这些差异,一旦我得到现有的代码工作。
一个例子的解决方案将不胜感激。
谢谢您的答复。刚刚试过你的代码,它返回以下错误: '致命错误:调用未定义的方法PhpOffice \ PhpWord \ Element \ Table :: setText()' 什么可能会出错? –
这意味着现有的(第一个)头元素是一个Table对象(而不是直接使用示例Text对象),也就是说,您只需要改变访问数据的方式:$ element1-> getRows()为您提供行,而您请继续阅读(详细信息取决于您在页眉和页脚中实际存在的内容以及要修改的部分) – ejuhjav
再次感谢您的建议。我改变了我以前的代码,并得到了这个工作。再次感谢。 –