gpt4 book ai didi

PHPWord 导出给出损坏的 Word 文件

转载 作者:可可西里 更新时间:2023-11-01 13:33:03 24 4
gpt4 key购买 nike

我使用了 PHPWord 站点的示例代码:http://phpword.codeplex.com/documentation当我尝试用 Word 打开它时,出现错误“Office Open XML 文件 test.docx 无法打开,因为内容有问题。”当我点击“详细信息”时,它只是说“文件已损坏,无法打开。”它确实让我修复它并打开它,但这对用户来说不是很友好......这是我正在使用的代码:

// Create a new PHPWord Object
$PHPWord = new PHPWord();

// Every element you want to append to the word document is placed in a section. So you need a section:
$section = $PHPWord->createSection();

// After creating a section, you can append elements:
$section->addText('Hello world!');

// You can directly style your text by giving the addText function an array:
$section->addText('Hello world! I am formatted.', array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));

// If you often need the same style again you can create a user defined style to the word document
// and give the addText function the name of the style>:
$PHPWord->addFontStyle('myOwnStyle', array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232'));
$section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');

// You can also putthe appended element to local object an call functions like this:
$myTextElement = $section->addText('Hello World!');



header('Content-Type: application/vnd.ms-word');
header('Content-Disposition: attachment;filename="test.docx"');
header('Cache-Control: max-age=0');
// At least write the document to webspace:
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');

如您所见,我确实使用 php://output 作为那里的保存。关于如何摆脱腐败的任何想法。我确实打开了 zip,看到在 document.xml 的末尾似乎有一个空行。也许这是造成它的原因?

谢谢!

最佳答案

只需添加 ob_clean();在输出之前!

ob_clean();
$objWriter->save('php://output');

这将清除您的输出,现在您可以安全地生成 docx 文件了:)

关于PHPWord 导出给出损坏的 Word 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8576964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com