16APRILIE2010byALIN Theproblem IneededtogenerateaWorddocum entfromPHP(moreexactly,fromCodeIgniter). TheWorddocumentactsasatemplate whichreceivesvalue sfromPHPandadds themtopred efinedplaceholders.Also,theWorddocumentmustbeabletocontain dynamicallygeneratedimages. Candidatesolutions: using an“exportto.doc(x)”l i brary(e.g.PHPLiveDocx(hp://ww w.phplivedocx.org),PHPWord (hp://phpword.codeplex.com/))–inv olv essomecomplications:integrationwithCodeIgniterissues, theneedtoexpresstheWorddocumentmarkupusi ng PHP(notgood fora10pag edocument,norfor templatechanges); 1. generatingtheWorddocumentusing COM(hp://www.phpbuilder.com/columns /yunus20031124.php3?page=2)–whilepromising,itinvolv esrequirementsthataren’talways achievable:aWindowsserverwithMicrosoftWordinstalledonit;also,asMi crosoftexplains (hp://support.microsoft.com/kb/257757),thissolutionmaycauseslowprocessingontheserver,due tothefactthatOfficewasn’tintendedtobeaserver‐si desolution; 2. e xporting toRTF(hp://www.phpclasses.org/browse/file/7158.html)–RTFisadocum entedformat (hp://www.microsoft.com/downloads/details.aspx? FamilyId=DD422B8D‐FF06‐4207‐ B476‐6B5396A18A2B&displaylang=en)(insome>270pag es),soitshouldpl ay nice lywithPHP.After look ingatsomeRTFdocumentscontainingimages,Ifoundou tthat(1)theirsizewasincreasingqui te fastasnewimageswereaddedand(2)theimageformat wasn’tqui teeasytorepresent; 3. outpuing(X)HTML ,withWordheadersandextension(hp://www.phpclasses.org/package/2631‐ PHP‐Create‐Microsoft‐Word‐document‐without‐COM‐objects.html)–anicehac kthatgavemesome hope.Iusedthisideainadifferentmanner:IcreatedawellformedWorddocum entandthensavedit as“WebPage,Filtered”.Allwentwellunti l Ibumpedintothissol ution’smajordrawback:inabilityto embedimages–onlylink stothem.Obviously,thisaffectsthe generateddocuments’portability.Of course,Itriedusi ng Base64encodedimages(hp:// dean.edwards.name/weblog/2005/06/base64‐ie/); theywerevisiblewhenIopenedthedocum entinabrowser,butWordwasn’tabletodisplaythem (hp://social.msdn.microsoft.com/Forums/en/innovateonoffice/thread/9d0c628b‐d6e4‐4ab8‐8f6c‐ c4c05b7f01e3).SoItriedotherhacks(likeexporting toMHTML,or“SingleFileWebPage”),and servingthatwithWordheadersandextension,butthe resultwasn’tgoodeither. 4. Mysolution Aboutthese ads(hp://en.wordpress.com/about‐these‐ads/) Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 1 of 6 6/23/2013 12:02 A M Whilelook ing forsolutions,Itrie dMicrosoft’sWord2003XMLformat ( h p://en.wi ki pedia.org /wik i/Microsoft_Office_2003_XML_formats)(also,checkouttheXMLschemas(schemata?) (hp://www.microsoft.com/downloads/details.aspx? FamilyId=FE118952‐3547‐420A‐ A412‐00A2662442D9&displaylang=en)forthisformat).Ifollowedthesamepaern: ‐createanicelyformaeddocum ent, ‐exportittoWord2003XML, ‐serveitfromPHPwithspeci alhe adersand.docextension. Itwaspureblisstofindoutthatinthisformatthe imag esaresavedinafamiliarbase64encoding(easily doableusing PHP’sbase64_encode()(hp://php.ne t/manual/en/function.base64‐encode.php)).Problem (almost)solved!“A lmo st ” becausenowIhavetogeneratetheproperXMLtagssurrounding the em beddedimages–itonlyrequiressomeresearch. So,withonlyplaintextyoucanhaveaproperlyforma edWorddocumentwithembeddedima ges!…andPHP canhandleplaintextqu itee asily… I’vetrie dtoopentheWord2003XMLdocum entinOpenOffice.org3.1.Unfortunately,Writ erwasn’t fooledbythe.docextensionandopenedthedocum entasplaintext.Onlyafterchangingthedocum ent’s extensionto.xml,theeditoropeneditcorrectly.So,thedocum entsareportableafterall. HowthislooksinmyCod eIgni ter context? TheView Fi r st,ItookthegeneratedXMLdocum ent,prepareditabitandplaceditintotheapplication’sviews folder.The“preparation”consiste din: ‐changingthefile’sextensionfrom.xmlto.php; ‐makingsurethefileformatisUTF‐8withoutBOM(hp://www.w3.org/International/questions /qa‐utf8‐bom );thelineendingIchoseisCRLF,butyoumaytrythenon‐Windowsalternatives(CRorLF); ‐reform aing the XMLfromahugeone‐linertoamorereadableform(MicrosoftExpressionWeb (hp://www.microsoft.com/expression/default.aspx)doesagreatjobatformaingXML/(X)HTML documents); ‐removi ng thetabcharacters(\t)fromtheresultingdocum ent,sothatthe ydon’tmesstheoutput; ‐changingtheXMLheadingsforthemtobeinterpretedasintended: from: to: ‐puingtheappropriatePHPvariablesintothe irviewplaceholders: Youmayalsotrytouse{templates}(justremem bertoloadthete mplateparserl i brary (hp://codeigniter.com/user_guide/libraries/parser.html)beforehand:$this‐>load‐>l i brary (‘parser ’);). 1 2 <?xmlversion="1.0"encoding="utf‐8" standalone="yes"?> <?mso‐applicationprogid="Word.Document"?> 1 2 <?phpecho'<?xmlversion="1.0" encoding="utf‐8" standalone="yes"?> <?mso‐applicationprogid="Word.Document" ?>';?> 1 <?phpecho$report_date;?> Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 2 of 6 6/23/2013 12:02 A M TheController Ipreparedthedatatobesenttotheviewasusual(hp://codeigniter.com/user_guide/general /views.html).Beforeloading theviewIadde dseveral headers,justtomakesureeverythinggoesOK: Ihopethishelps.Oh,did Imentionthatthe sameideacanbeusedtoobtainformaedExcel spreadsheets(see xl s‐sam ple.xls(hp://k lewos.files.wordpress.com/2010/04/xls‐sample.xls))? P.S.AmoremaintainableandpropersolutionwouldbetouseXMLandXSLT(somethinglikethis (hp://msdn.microsoft.com/en‐us/library/ee840137(office.12).aspx),albeittheexamplereferstotheOffice OpenXMLformat),butthismightnotbeasquick assimpl yfilling placehold ersinaview. Update(5July2010) Seeatrivialdem ohere(hp://mydemo.ueuo.com/).Useittogenerateasam pl edocum ent;thendrag the documenttoNotepadoranotherplaintexteditortoobservethe xm l . Ci teșteși: RunningMultipleMySQLScriptsfromaBatchFile–theQuickandDirtyWay (hp://klewos.wordpress.com/2010/03/30/running‐multiple‐mysql‐scripts‐from‐a‐batch‐file‐the‐qui ck ‐ and‐dirty ‐way/) Reinventezroata(hp://klewos.wordpress.com/2010/03/20/reinventez‐roata/) Unhackordinar(hp://klewos.wordpress.com/2010/ 01/17/un‐hack‐ordinar/) CRUDînCodeIgniter(hp://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 Thisentrywasposted inCalculatoare andtaggedCodeIgniter,fileformat ,MicrosoftWord,PHP,XML. 1 2 3 4 5 6 7 8 9 #$doc_dataisthearraythatissenttotheview $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;//neededsothatanyredirect()afterthislinedoesn'tmessupthings, Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 3 of 6 6/23/2013 12:02 A M Bookm arkthepermalink. 11comentarii akashspune: 31august2010la11:27 Hiall, InexportingMSworddocum entsusing code igniterIamapplyingthefollowing codeandworking fine,ButIneedtoformatthe MS worddocum entforpagesetup,suchasheightwidthandlandscape orportraitetc. Anyideaortutorialtodothisplease? $dat a=“MyData”; $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:aachment;filename=\”mydocumen tname.doc\”ʺ); echo$html; exit; Thanksinadvance akash Alinspune: 31august2010la11:42 Hello, Fi r styouneedtodesig nyourdocument(includingformaing andpag esetup)using Word.Afte rthat youexportthedocum entto.xml(Word2003XML)andyoudojustasIdescribedinthisarticle.It’s preystraightforward. Ifyouwanttoeditdocum entpropertiesafterwards lookforthedocumentpropertiesinthe .xml, they’requiteeasytofigureout. akashspune: 31august2010la13:15 Hello, IfIwantexportingitdi rectly to.docformatthenwhereIshallchange?Andwhatwillbethechangein myviewfile? Thanks Akash Alinspune: 31august2010la13:27 Sorry ,buthaveyoureadandtrie dthe approachesmentionedinthe article ?Itwasallaboutsaving Worddocum entsinaspeci alxm lformatwitha.docextension.Thesedocum entscanbeopenedby Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 4 of 6 6/23/2013 12:02 A M MSWordandOpenOffice.org.Thealternativesarealsomentionedinthearticle,sotake yourtime, explorethem,findouttheirstrengthsandweaknesses,andchooseanappropriatesolutionforyour concreteneeds.I’mafraidthat’saboutallIcandoforyou. YOGES Hspune: 13noiembrie2010la07:29 Whilecreating.docfileonFlyasmentionedabovehowcanipu tanimageintomydocuments(Not using ashyperlinkoronlineimages). AsinsertingLogoorheaderorvariousotherimagesdisplay edonwebpag es. Alinspune: 13noiembrie2010la12:26 Fi r st,youneedtostudyabitthe wayWordXML2003handlesimages.You’dhavetocreateasimple documentinthisformat,inwhichyoushouldincludeanimage.Seehowit’snestedintheXML hierarchy(i.e.tagslikew:pict,w:binData,v:shape,v:imagedata).Thenyouneedtooutputtheimage’s contentinabase64encodedformandtoconvertpixelstopoi ntsforthe appropriateaributes(he ight, width).Again,afterabitofstudyingthereshouldbenoproblem . Here’ saglimpseofwhatImean: Ofcourse,youcanusealoop toadda numberofimagesinsuccession. HTH. 3rdbitspu ne: 15decem brie2010la17:02 Ihadaprobl em withtheencodingofspecialchars,forexamplewiththeä(Umlaut ,usedingerman). MSOfficedidn’topenedthe affecteddocum ents,soihadtodosomeconversions.Itdon’tworkwith yourdem oneither. //Convertpossiblyspecialcharscontainingstring toUTF‐8 $content=utf8_encode($content) //Informthebrowserthat it'sUTF‐8encoded content header('Content‐Type:application/xml;charset=UTF‐8'); btw.forabeerbrowsercompatibility youshouldusetheContent‐Type“application/xml”insteadof “text/xml” hp://www.g rauw.nl/blog/entry/489 Alinspune: 1 2 3 4 5 6 7 8 // <w:pict> <w:binDataw:name="wordml://<?phpecho$file_name;?>"xml:space="preserve">< ? <v:shapeid="img<?phpecho$i.$j;?>"type="#_x0000_t75"style="width:<?phpe c <v:imagedatasrc="wordml://<?phpecho$file_name;?>"o:title="application_vi e </v:shape> </w:pict> // Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 5 of 6 6/23/2013 12:02 A M 16decem brie2010la11:52 Sorry foransweringsolateandthankyouforpoi ntingoutthisencodingissue.Thedemowassetup onlytoshowhowthe “trick”describedaboveworksanddidn’tgoallthewaytohandleencodingsand whatnot. karthickspune: 24mai2011la09:17 Hianyonecangivemethewholestructureofcoding….iamlilebitconfusedhowtostartandwhere tofinishthe coding… EduardoRamosspune: 22februarie2012la10:51 haveyoutriedphpdocx:hp://www .phpdocx.com Blog uieștepeWordPress.com.|Theme:DuskToDawnbyAutomaic. Follow Poweredb y WordPress.co m Using PHP to Fill a Word Document (Quick Tip) | Klewos http://klewos.wordpress.com/2010/04/16/using-php-to-fill-a-word-docum 6 of 6 6/23/2013 12:02 A M . 01/17/un‐hack‐ordinar/) CRUDînCodeIgniter(hp://klewos.wordpress.com/2010/03/02/crud‐in‐codeigniter/) /click?wylz843osj_mSYioeBKwPwAAAAAAAPA_5kmIqHgSsD_DKXPzjeiyP6SGw5PuBoVAlSTggiPmrg5 3 gDrPAAAy30AAgUCAQIAAIIADCbvOgAAAAA./cnd=%218wV‐NA iT2VUQ1pnJAhjF2gggAA. alhe adersand.docextension. Itwaspurebliss to findoutthatinthisformatthe imag esaresavedin a familiarbase64encoding(easily doable using PHP sbase64_encode()(hp:/ /php. ne t/manual/en/function.base64‐encode .php) ).Problem (almost)solved! A. entforpagesetup,suchasheightwidthandlandscape orportraitetc. Anyideaortutorial to dothisplease? $dat a =“MyData”; $html=$this‐>load‐>v iew(‘myv iewfile’,$data,true); header(“Content‐Type:application/v