CodeIgniter PHPWord using as third_party

Jeremy picture Jeremy · Sep 25, 2014 · Viewed 7.4k times · Source

I am trying to use PHPWord and having a difficulties to use it.

This my code within application/libraries/words.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH."/third_party/PhpWord/Autoloader.php"; 

\PhpOffice\PhpWord\Autoloader::register(); \\NOT SURE IF THIS IS CORRECT

class Word extends PhpWord { 
    public function __construct() { 
        parent::__construct(); 
    } 
}

Based on PHPWord github, i must use it like this:

Alternatively, you can download the latest release from the releases page. In this case, you will have to register the autoloader.

require_once 'path/to/PhpWord/src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register(); // WHERE SHOULD I PUT THIS?

When i try to load the library from my controller as such:

$this->load->library('word');

it gives me error that says:

Fatal error: Class 'PhpWord' not found in C:\xampp\htdocs\path\to\application\libraries\Word.php on line 7

i tried to extends the Autoloader class, but PHP still complains that it can't found Autoloader.php.

when i do

file_exist(APPPATH."/third_party/PhpWord/Autoloader.php") // Similarly with PhpWord.php

it returns 1.

Does anyone know how to fix this?

Answer

black_art picture black_art · Mar 1, 2015

From Russia with love;) Use like this in library for CodeIgniter:

<?php 
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');


    require_once  APPPATH.'/libraries/PHPWord/src/PhpWord/Autoloader.php';
    use PhpOffice\PhpWord\Autoloader as Autoloader;
    Autoloader::register();

    class Word extends Autoloader {

    }

    ?>

In controller like code from samples:

$this->load->library('word');
/* remove ;)
#require_once 'PHPWord/src/PhpWord/Autoloader.php';
#PhpOffice\PhpWord\Autoloader::register();
*/

// Template processor instance creation
echo date('H:i:s') , ' Creating new TemplateProcessor instance...' ;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('text.docx');


$templateProcessor->setValue('sss','123');

echo date('H:i:s'), ' Saving the result document...';
$templateProcessor->saveAs('test1.docx');

Tested it works!