Tải bản đầy đủ (.pdf) (6 trang)

Using PHP to fill a word document

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (252.81 KB, 6 trang )

16APRILIE2010byALIN
Theproblem
IneededtogenerateaWorddocum entfromPHP(moreexactly,fromCodeIgniter).
TheWorddocumentactsasatemplate whichreceivesvalue sfromPHPandadds
themtopred efinedplaceholders.Also,theWorddocumentmustbeabletocontain
dynamicallygeneratedimages.
Candidatesolutions:
using an“exportto.doc(x)”l i brary(e.g.PHPLiveDocx(hp://ww w.phplivedocx.org),PHPWord
(hp://phpword.codeplex.com/))–inv olv essomecomplications:integrationwithCodeIgniterissues,
theneedtoexpresstheWorddocumentmarkupusi ng PHP(notgood fora10pag edocument,norfor
templatechanges);
1.
generatingtheWorddocumentusing COM(hp://www.phpbuilder.com/columns
/yunus20031124.php3?page=2)–whilepromising,itinvolv esrequirementsthataren’talways
achievable:aWindowsserverwithMicrosoftWordinstalledonit;also,asMi crosoftexplains
(hp://support.microsoft.com/kb/257757),thissolutionmaycauseslowprocessingontheserver,due
tothefactthatOfficewasn’tintendedtobeaserver‐si desolution;
2.
e xporting toRTF(hp://www.phpclasses.org/browse/file/7158.html)–RTFisadocum entedformat
(hp://www.microsoft.com/downloads/details.aspx? FamilyId=DD422B8D‐FF06‐4207‐
B476‐6B5396A18A2B&displaylang=en)(insome>270pag es),soitshouldpl ay nice lywithPHP.After
look ingatsomeRTFdocumentscontainingimages,Ifoundou tthat(1)theirsizewasincreasingqui te
fastasnewimageswereaddedand(2)theimageformat wasn’tqui teeasytorepresent;
3.
outpuing(X)HTML ,withWordheadersandextension(hp://www.phpclasses.org/package/2631‐
PHP‐Create‐Microsoft‐Word‐document‐without‐COM‐objects.html)–anicehac kthatgavemesome
hope.Iusedthisideainadifferentmanner:IcreatedawellformedWorddocum entandthensavedit
as“WebPage,Filtered”.Allwentwellunti l Ibumpedintothissol ution’smajordrawback:inabilityto
embedimages–onlylink stothem.Obviously,thisaffectsthe generateddocuments’portability.Of
course,Itriedusi ng Base64encodedimages(hp:// dean.edwards.name/weblog/2005/06/base64‐ie/);
theywerevisiblewhenIopenedthedocum entinabrowser,butWordwasn’tabletodisplaythem


(hp://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/9d0c628b‐d6e4‐4ab8‐8f6c‐
c4c05b7f01e3).SoItriedotherhacks(likeexporting toMHTML,or“SingleFileWebPage”),and
servingthatwithWordheadersandextension,butthe resultwasn’tgoodeither.
4.
Mysolution
Aboutthese ads(hp://en.wordpress.com/about‐these‐ads/)
Using PHP to Fill a Word Document (Quick Tip) | Klewos
1 of 6 6/23/2013 12:02 A
M
Whilelook ing forsolutions,Itrie dMicrosoft’sWord2003XMLformat (
h
p://en.wi ki pedia.org
/wik i/Microsoft_Office_2003_XML_formats)(also,checkouttheXMLschemas(schemata?)
(hp://www.microsoft.com/downloads/details.aspx? FamilyId=FE118952‐3547‐420A‐
A412‐00A2662442D9&displaylang=en)forthisformat).Ifollowedthesamepaern:
‐createanicelyformaeddocum ent,
‐exportittoWord2003XML,
‐serveitfromPHPwithspeci alhe adersand.docextension.
Itwaspureblisstofindoutthatinthisformatthe imag esaresavedinafamiliarbase64encoding(easily
doableusing PHP’sbase64_encode()(hp://php.ne t/manual/en/function.base64‐encode.php)).Problem
(almost)solved!“A lmo st ” becausenowIhavetogeneratetheproperXMLtagssurrounding the
em beddedimages–itonlyrequiressomeresearch.
So,withonlyplaintextyoucanhaveaproperlyforma edWorddocumentwithembeddedima ges!…andPHP
canhandleplaintextqu itee asily…
I’vetrie dtoopentheWord2003XMLdocum entinOpenOffice.org3.1.Unfortunately,Writ erwasn’t
fooledbythe.docextensionandopenedthedocum entasplaintext.Onlyafterchangingthedocum ent’s
extensionto.xml,theeditoropeneditcorrectly.So,thedocum entsareportableafterall.
HowthislooksinmyCod eIgni ter
context?
TheView

Fi r st,ItookthegeneratedXMLdocum ent,prepareditabitandplaceditintotheapplication’sviews
folder.The“preparation”consiste din:
‐changingthefile’sextensionfrom.xmlto.php;
‐makingsurethefileformatisUTF‐8withoutBOM(hp://www.w3.org/International/questions
/qa‐utf8‐bom );thelineendingIchoseisCRLF,butyoumaytrythenon‐Windowsalternatives(CRorLF);
‐reform aing the XMLfromahugeone‐linertoamorereadableform(MicrosoftExpressionWeb
(hp://www.microsoft.com/expression/default.aspx)doesagreatjobatformaingXML/(X)HTML
documents);
‐removi ng thetabcharacters(\t)fromtheresultingdocum ent,sothatthe ydon’tmesstheoutput;
‐changingtheXMLheadingsforthemtobeinterpretedasintended:
from:
to:
‐puingtheappropriatePHPvariablesintothe irviewplaceholders:
Youmayalsotrytouse{templates}(justremem bertoloadthete mplateparserl i brary
(hp://codeigniter.com/user_guide/libraries/parser.html)beforehand:$this‐>load‐>l i brary (‘parser ’);).
1
2
<?xmlversion="1.0"encoding="utf‐8" standalone="yes"?>
<?mso‐applicationprogid="Word.Document"?>
1
2
<?phpecho'<?xmlversion="1.0" encoding="utf‐8" standalone="yes"?>
<?mso‐applicationprogid="Word.Document" ?>';?>
1 <?phpecho$report_date;?>
Using PHP to Fill a Word Document (Quick Tip) | Klewos
2 of 6 6/23/2013 12:02 A
M
TheController
Ipreparedthedatatobesenttotheviewasusual(hp://codeigniter.com/user_guide/general
/views.html).Beforeloading theviewIadde dseveral headers,justtomakesureeverythinggoesOK:

Ihopethishelps.Oh,did Imentionthatthe sameideacanbeusedtoobtainformaedExcel
spreadsheets(see
xl s‐sam ple.xls(hp://k lewos.files.wordpress.com/2010/04/xls‐sample.xls))?
P.S.AmoremaintainableandpropersolutionwouldbetouseXMLandXSLT(somethinglikethis
(hp://msdn.microsoft.com/en‐us/library/ee840137(office.12).aspx),albeittheexamplereferstotheOffice
OpenXMLformat),butthismightnotbeasquick assimpl yfilling placehold ersinaview.
Update(5July2010)
Seeatrivialdem ohere(hp://mydemo.ueuo.com/).Useittogenerateasam pl edocum ent;thendrag the
documenttoNotepadoranotherplaintexteditortoobservethe xm l .
Ci teșteși:
RunningMultipleMySQLScriptsfromaBatchFile–theQuickandDirtyWay
(hp://klewos.wordpress.com/2010/03/30/running‐multiple‐mysql‐scripts‐from‐a‐batch‐file‐the‐qui ck ‐
and‐dirty ‐way/)
Reinventezroata(hp://klewos.wordpress.com/2010/03/20/reinventez‐roata/)
Unhackordinar(hp://klewos.wordpress.com/2010/ 01/17/un‐hack‐ordinar/)
CRUDînCodeIgniter(hp://klewos.wordpress.com/2010/03/02/crud‐in‐codeigniter/)
/click?wylz843osj_mSYioeBKwPwAAAAAAAPA_5kmIqHgSsD_DKXPzjeiyP6SGw5PuBoVAlSTggiPmrg5
3
gDrPAAAy30AAgUCAQIAAIIADCbvOgAAAAA./cnd=%218wV‐NA iT2VUQ1pnJAhjF2gggAA /r
e
word‐docum ent‐
q
ui ck ‐ti
p
%2F/click enc=
h

p
%3A%2F%2Fl
p

.kin
g
translate.com%2F%3Fa
pp
id%3D13
3
Thisentrywasposted inCalculatoare andtaggedCodeIgniter,fileformat ,MicrosoftWord,PHP,XML.
1
2
3
4
5
6
7
8
9
#$doc_dataisthearraythatissenttotheview

$filename="report".date('dmY‐his').".doc";
header("Content‐Type:application/xml;charset=UTF‐8");
header("Expires:0");
header("Cache‐Control:must‐revalidate,post‐check=0,pre‐check=0");
header("content‐disposition:attachment;filename=$filename");
$this‐>load‐>view('templates/default',$doc_data);
return;//neededsothatanyredirect()afterthislinedoesn'tmessupthings,
Using PHP to Fill a Word Document (Quick Tip) | Klewos
3 of 6 6/23/2013 12:02 A
M
Bookm arkthepermalink.
11comentarii

akashspune:
31august2010la11:27
Hiall,
InexportingMSworddocum entsusing code igniterIamapplyingthefollowing codeandworking
fine,ButIneedtoformatthe MS worddocum entforpagesetup,suchasheightwidthandlandscape
orportraitetc.
Anyideaortutorialtodothisplease?
$dat a=“MyData”;
$html=$this‐>load‐>v iew(‘myv iewfile’,$data,true);
header(“Content‐Type:application/v nd.ms‐word”);
header(“Expires:0″);
header(“Cache‐Control:must‐rev alidate,post‐check=0,pre‐check=0″);
header(“Content‐disposition:aachment;filename=\”mydocumen tname.doc\”ʺ);
echo$html;
exit;
Thanksinadvance
akash
Alinspune:
31august2010la11:42
Hello,
Fi r styouneedtodesig nyourdocument(includingformaing andpag esetup)using Word.Afte rthat
youexportthedocum entto.xml(Word2003XML)andyoudojustasIdescribedinthisarticle.It’s
preystraightforward.
Ifyouwanttoeditdocum entpropertiesafterwards
lookforthedocumentpropertiesinthe .xml,
they’requiteeasytofigureout.
akashspune:
31august2010la13:15
Hello,
IfIwantexportingitdi rectly to.docformatthenwhereIshallchange?Andwhatwillbethechangein

myviewfile?
Thanks
Akash
Alinspune:
31august2010la13:27
Sorry ,buthaveyoureadandtrie dthe approachesmentionedinthe article ?Itwasallaboutsaving
Worddocum entsinaspeci alxm lformatwitha.docextension.Thesedocum entscanbeopenedby
Using PHP to Fill a Word Document (Quick Tip) | Klewos
4 of 6 6/23/2013 12:02 A
M
MSWordandOpenOffice.org.Thealternativesarealsomentionedinthearticle,sotake yourtime,
explorethem,findouttheirstrengthsandweaknesses,andchooseanappropriatesolutionforyour
concreteneeds.I’mafraidthat’saboutallIcandoforyou.
YOGES Hspune:
13noiembrie2010la07:29
Whilecreating.docfileonFlyasmentionedabovehowcanipu tanimageintomydocuments(Not
using ashyperlinkoronlineimages).
AsinsertingLogoorheaderorvariousotherimagesdisplay edonwebpag es.
Alinspune:
13noiembrie2010la12:26
Fi r st,youneedtostudyabitthe wayWordXML2003handlesimages.You’dhavetocreateasimple
documentinthisformat,inwhichyoushouldincludeanimage.Seehowit’snestedintheXML
hierarchy(i.e.tagslikew:pict,w:binData,v:shape,v:imagedata).Thenyouneedtooutputtheimage’s
contentinabase64encodedformandtoconvertpixelstopoi ntsforthe appropriateaributes(he ight,
width).Again,afterabitofstudyingthereshouldbenoproblem .
Here’ saglimpseofwhatImean:
Ofcourse,youcanusealoop toadda
numberofimagesinsuccession.
HTH.
3rdbitspu ne:

15decem brie2010la17:02
Ihadaprobl em withtheencodingofspecialchars,forexamplewiththeä(Umlaut ,usedingerman).
MSOfficedidn’topenedthe affecteddocum ents,soihadtodosomeconversions.Itdon’tworkwith
yourdem oneither.
//Convertpossiblyspecialcharscontainingstring
toUTF‐8
$content=utf8_encode($content)
//Informthebrowserthat it'sUTF‐8encoded content
header('Content‐Type:application/xml;charset=UTF‐8');
btw.forabeerbrowsercompatibility youshouldusetheContent‐Type“application/xml”insteadof
“text/xml”
hp://www.g rauw.nl/blog/entry/489
Alinspune:
1
2
3
4
5
6
7
8
//
<w:pict>
<w:binDataw:name="wordml://<?phpecho$file_name;?>"xml:space="preserve"><
?
<v:shapeid="img<?phpecho$i.$j;?>"type="#_x0000_t75"style="width:<?phpe
c
<v:imagedatasrc="wordml://<?phpecho$file_name;?>"o:title="application_vi
e
</v:shape>

</w:pict>
//
Using PHP to Fill a Word Document (Quick Tip) | Klewos
5 of 6 6/23/2013 12:02 A
M
16decem brie2010la11:52
Sorry foransweringsolateandthankyouforpoi ntingoutthisencodingissue.Thedemowassetup
onlytoshowhowthe “trick”describedaboveworksanddidn’tgoallthewaytohandleencodingsand
whatnot.
karthickspune:
24mai2011la09:17
Hianyonecangivemethewholestructureofcoding….iamlilebitconfusedhowtostartandwhere
tofinishthe coding…
EduardoRamosspune:
22februarie2012la10:51
haveyoutriedphpdocx:hp://www .phpdocx.com
Blog uieștepeWordPress.com.|Theme:DuskToDawnbyAutomaic.
Follow
Poweredb
y
WordPress.co
m
Using PHP to Fill a Word Document (Quick Tip) | Klewos
6 of 6 6/23/2013 12:02 A
M

×