如何使用PhpWord读取Doc文件?

时间:2013-12-12 21:53:31

标签: php phpword

最近我下载了我从github下载的php字,但我不知道如何通过这个阅读word文件? 这个lib没有任何帮助。我看到一个像php excel一样的文件,但不知道如何使用。下面的文件:simple01 sample.php

<?php

error_reporting(E_ALL);

if(php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
    define('EOL', PHP_EOL);
}
else {
    define('EOL', '<br />');
}

require_once '../src/PHPWord.php';

// New Word Document
echo date('H:i:s') , " Create new PHPWord object" , EOL;
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);

$section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);

$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');

// Save File
echo date('H:i:s') , " Write to Word2007 format" , EOL;
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save(str_replace('.php', '.docx', __FILE__));

echo date('H:i:s') , " Write to OpenDocumentText format" , EOL;
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'ODText');
$objWriter->save(str_replace('.php', '.odt', __FILE__));

echo date('H:i:s') , " Write to RTF format" , EOL;
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'RTF');
$objWriter->save(str_replace('.php', '.rtf', __FILE__));


// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;

// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
?>

的问候,阿赫桑

2 个答案:

答案 0 :(得分:4)

PHPWord 0.8为阅读DOCX提供了基本支持。 See the code sample here

答案 1 :(得分:0)

https://github.com/PHPOffice/PHPWord/blob/develop/composer.json

您需要src文件夹,否则它将不起作用。您可以从https://github.com/PHPOffice/PHPWord/tree/develop/src复制src文件夹。

<?php
try
{
    require 'vendor/autoload.php';
    $name = basename(__FILE__, '.php');
    $name="urine2";
    $source = __DIR__ . "/{$name}.docx";

    $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
    // Adding an empty Section to the document...
    $section = $phpWord->addSection();
    // Adding Text element to the Section having font styled by default...
    $section->addText($data);

    $name=basename(__FILE__, '.php');
    $source = __DIR__ . "/results/{$name}.html";

    // Saving the document as HTML file...
    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
    $objWriter->save($source);


}catch(Exception $e)
{
    echo $e->getLine();
    echo "<br>/";
    echo $e->getMessage();
    echo "<br/>";
    echo $e->getFile();
    exit;
}
echo "Generated successfully";