PHPWord导出提供损坏的Word文件 [英] PHPWord export giving Corrupt Word File

查看:314
本文介绍了PHPWord导出提供损坏的Word文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了PHPWord网站上的示例代码: http://phpword.codeplex.com/documentation 当我尝试用Word打开它时,出现错误由于内容存在问题,无法打开Office Open XML文件test.docx".当我单击详细信息"时,它只是说文件已损坏,无法打开."它的确可以让我修复并打开它,但这不是非常用户友好...这是我正在使用的代码:

I used the example code from PHPWord's site: http://phpword.codeplex.com/documentation And when I try and open it with Word I get the error "The Office Open XML file test.docx cannot be opened because there are problems with the contents." and when I click "Details" It simply says "The file is corrupt and cannot be opened." It does let me repair it and open it, but that wouldn't be very user friendly... Here is the code I'm using:

// 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的末尾出现了空白行.也许是造成这种情况的原因?

As you can see I did use php://output as the save there. Any ideas on how to get rid of the corruption. I did open the zip and saw that at the end of document.xml it appears there is blank line. Maybe that is causing it?

谢谢!

推荐答案

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

Just add ob_clean(); before output it!

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

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

This will clean you'r output, and now you are safe to generate docx file :)

这篇关于PHPWord导出提供损坏的Word文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆