TIL
PHPWord - docx 파일을 화면에 보이게 하기
개발따라김양
2024. 12. 5. 12:52
1. 문제상황
- docx 파일을 입력 받아 저장시키는 상황에서 화면에서 파일을 페이지로 띄워야 했습니다.
- PHPWord 라이브러리를 알게 되어 적용시켰습니다.
2. 문제 해결
1. PHPWord 설치하기
composer require phpoffice/phpword
2. 경로 받아와서 화면에 보이기
<?php
// Composer를 통해 PHPWord 라이브러리 사용
require_once '../vendor/autoload.php'; // 라이브러리 위치
$docxFilePath = isset($_GET['file']) ? $_GET['file'] : '기본 파일 경로'; //파일 경로 동적 할당
if (file_exists($docxFilePath)) {
try {
$phpWord = \PhpOffice\PhpWord\IOFactory::load($docxFilePath);
$htmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
ob_start();
$htmlWriter->save('php://output');
$htmlContent = ob_get_clean();
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOCX 파일 보기</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body style="width: 100%;">
<div class="docx_wrap">
<?= $htmlContent; ?>
</div>
</body>
</html>
<?php
} catch (Exception $e) {
echo "<p>PHPWord 변환 중 오류 발생: " . $e->getMessage() . "</p>";
}
} else {
echo "<p>파일이 존재하지 않습니다: $docxFilePath</p>";
}
?>