Creating Ms Word Document using CodeIgniter and PHPWord

One of my reader – Don Lafferty – told us that integrating PHPWord into CodeIgniter is also as easy as integrating PHPExcel into CodeIgniter. So, I decided to give it a try and it really does so simple.

What is PHPWord? From github:

[box type=”info”] PHPWord is a library written in PHP that create word documents. No Windows operating system is needed for usage because the result are docx files (Office Open XML) that can be opened by all major office software.[/box]

Notes: As I write this, PHPWord can create .docx, .rtf and .odt file.

  • Without more a do, go download the required package

[button link=”http://codeigniter.com/” newwindow=”yes” color=”orange”] Download CodeIgniter[/button]

[button link=”https://github.com/PHPOffice/PHPWord” newwindow=”yes” color=”black”]Download PHPWord[/button]

  • Extract PHPWord (only extract PHPWord.php and PHPWord folder) into your CodeIgniter’s application/third_party
ci phpword extract file

Only extract those two

 

Your application/third_party will look like this

ci third_party folder

Your new third_party folder after adding PHPWord

  • Now, create a new library inside your CodeIgniter’s application/libraries. Let’s call it Word.php. Here’s the full source:

  • OK, it’s done.
  • Now we can call and use the Word library from within your controllers (examples are taken from PHPWord with minimal change):
  • Call/load the library and create new section (needed)

  • Adding some text and style it!

  • Adding some images! Watchout on how I add new image, don’t use base_url or site_url, PHPWord only take an absolute path to your server (it also means that you can’t insert image that isn’t hosted on your server)

  • Create a table and give some style

  • Lastly, give the Ms Word document as .docx file to users without saving it to server’s hard-disk.

  • Example result (opened using Ms Word 2007 and zoomed 50%)
ci and phpword example result

This is what our code generate. CodeIgniter + PHPWord = MS Word 2007 document

Now our CodeIgniter become more complete, we can create Excel file, create a PDF file and, in this tutorial, creating Microsoft Word 2007 document!

Leave a comment ?

29 Comments.

  1. Don Lafferty

    Yes, it was that easy. I didn’t try PHPPowerPoint but maybe you could give it a shot. I bet it’s just as easy.

    Thanks for making these posts. It shows just how powerful CI is.

  2. mas, kalau ada 25 kotak html, masing2 di harus isi dengan text yang beraturan ke 25 kotak tersebut, caranya ngisi enak lewat 1 form khusus isi 25 textedit kebawah dan 1x submit ? atau dari 25 kotak di klik 1x, isi text, save by modal window (jquery)sampe 25x ulang ?, mending mana dan nyaman mana ? thanks

    • kalau sudah diniatkan pakai jQuery, lebih baik diletakkan di satu form dan 1x submit saja.
      Karena isiannya kelihatannya banyak (25 buah), mending dibikin tabular atau accordion (jquery ui).

      • kalau kotaknya (text item-nya) di klik sebanyak 25x perulangan (5×5), baru klik tombol save …kurang nyaman ya ?

        • capek nge-klik nya.. 😛
          klo mau model begitu, user harus diaksih tau, dia harus ngeklik berapa kali lagi, biar ndak merasa putus asa ngisi form nya

          • ok mas, iya sih, (klik 1x , isi text, klik lagi utk save text di kotak tsb sampe 25 kotak terisi dan klik submit …kayane enak model form biasa menurun ke bawah tinggal di atur biar ndak keliatan ruwet

            thanks mas

  3. how can we save it on our server ?

    • so, instead of

      you should do:

  4. makasih, sukses nyoba semua tutorialnya di phpword kecuali untuk templatenya.
    yang ini:
    loadTemplate(‘Template.docx’);

    $document->setValue(‘Value1’, ‘Sun’);
    $document->setValue(‘Value2’, ‘Mercury’);
    $document->setValue(‘Value3’, ‘Venus’);
    $document->setValue(‘Value4’, ‘Earth’);
    $document->setValue(‘Value5’, ‘Mars’);
    $document->setValue(‘Value6’, ‘Jupiter’);
    $document->setValue(‘Value7’, ‘Saturn’);
    $document->setValue(‘Value8’, ‘Uranus’);
    $document->setValue(‘Value9’, ‘Neptun’);
    $document->setValue(‘Value10’, ‘Pluto’);

    $document->setValue(‘weekday’, date(‘l’));
    $document->setValue(‘time’, date(‘H:i’));

    $document->save(‘Solarsystem.docx’);
    ?>

    kenapa error terus di setValuenya?

  5. Thank you for the nice library. I was using a UTF-8 (unicode) fonts for the text which is to be generated in the word file.

    How do I do it ?

  6. Additionally how to set the format by the html tags ?

  7. Tri Pamungkas

    can you help me? i have tried implement ‘Template’ example file to CI, the idea is saving to client (not saving to server), but it didn’t work as expected

    here is the code

    class php_word_controller extends CI_Controller {
    function __construct() {
    parent::__construct();
    $this->load->library(‘word’);
    }
    function index() {
    $templatefile = FCPATH.’assets/Template.docx’;
    $PHPWord = $this->word;
    $section = $PHPWord->loadTemplate($templatefile);
    $section->setValue(‘Value1′,’Sun’);
    $section->setValue(‘Value2′,’Mercury’);
    $section->setValue(‘Value3′,’Venus’);
    $section->setValue(‘Value4′,’Earth’);
    $section->setValue(‘Value5′,’Mars’);
    $section->setValue(‘Value6′,’Jupiter’);
    $section->setValue(‘Value7′,’Saturn’);
    $section->setValue(‘Value8′,’Uranus’);
    $section->setValue(‘Value9′,’Neptun’);
    $section->setValue(‘Value10′,’Pluto’);
    $section->setValue(‘weekday’,date(‘l’));
    $section->setValue(‘time’,date(‘H:i’));
    $fname=”Test-Template-PHPWORD.docx”;
    header(‘Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document’); // mime type
    header(‘Content-Disposition: attachment;filename=”‘.$fname.'”‘); // tell browser what’s the file name
    header(‘Cache-Control: max-age=0′); // no cache
    $objWriter = PHPWord_IOFactory::createWriter($PHPWord,’Word2007’);
    $objWriter->save(‘php://output’);
    }
    }

  8. drackcyber

    mas gimana caranya load hasilnya ke view.. baru pelajari nie..

  9. liliangrong li

    I’m sorry to disturb you,how to generate html file to word?

    is there anything method or material?

    Look forward to your reply! thanks!


  10. $this->load->library(‘word’);
    $templateFile = APPPATH . ‘/templates/bentley.docx’;
    $newDoc = $this->word->loadTemplate($templateFile);

    $newDoc->setValue(‘Value1’, ‘Sun’);
    $newDoc->setValue(‘Value2’, ‘Mercury’);
    $newDoc->setValue(‘Value3’, ‘Venus’);
    $newDoc->setValue(‘Value4’, ‘Earth’);
    $newDoc->setValue(‘Value5’, ‘Mars’);
    $newDoc->setValue(‘Value6’, ‘Jupiter’);
    $newDoc->setValue(‘Value7’, ‘Saturn’);
    $newDoc->setValue(‘Value8’, ‘Uranus’);
    $newDoc->setValue(‘Value9’, ‘Neptun’);
    $newDoc->setValue(‘Value10’, ‘Pluto’);

    $newDoc->setValue(‘weekday’, date(‘l’));
    $newDoc->setValue(‘time’, date(‘H:i’));

    //$newDoc->save(‘Solarsystem.docx’);

    // Save File / Download (Download dialog, prompt user to save or simply open it)
    $filename=’Solarsystem.docx’; //save our document as this file name
    //$newDoc->save($filename);
    header(‘Content-Description: File Transfer’);
    header(‘Content-type: application/force-download’);
    header(‘Content-Disposition: attachment; filename=’.basename($filename));
    header(‘Content-Transfer-Encoding: binary’);
    header(‘Content-Length: ‘.filesize($filename));
    readfile($filename);

    $this->index(‘download document here’);

    Worked perfectly, saved to the client

  11. Hi, I’ve used you tutorial in a project I created a few months ago and I can say it really is great. Now, I was wondering if I can do this vice versa?
    I mean word to php.
    Thanks.

    • can you explain how to execute word.php file it give following error

      Parse error: syntax error, unexpected ‘required’ (T_STRING) in C:\xampp\htdocs\word_db\CodeIgniter-3.0.6\application\views\welcome_message.php on line 3
      A PHP Error was encountered

      Severity: Parsing Error

      Message: syntax error, unexpected ‘required’ (T_STRING)

      Filename: views/welcome_message.php

      Line Number: 3

      Backtrace:

  12. arif fathurohman

    Hi, thank you very much, it’s very easy to implement
    😀

  13. Fatal error: Class ‘PHPWord_DocumentProperties’ not found in C:\xampp\htdocs\Employee\application\third_party\PHPWord.php on line 76

  14. ko salah gan

    Fatal error: Class ‘PHPWord_DocumentProperties’ not found in C:\xampp\htdocs\Employee\application\third_party\PHPWord.php on line 76

  15. waqas khan

    it give me this error plz help
    Class ‘PhpWord’ not found in C:\www\fleet_management\application\libraries\Word.php on line 5

  16. I have Same error i thing it’s a problem of version.
    Need Help too

  17. how to read doc file in ci through this library

Leave a Reply

Trackbacks and Pingbacks:

%d bloggers like this: