programing tip

Linux에서 PHP를 사용하여 Word 문서 만들기

itbloger 2020. 12. 8. 07:47
반응형

Linux에서 PHP를 사용하여 Word 문서 만들기


PHP가 Linux 환경에서 워드 문서를 생성하는 데 사용할 수있는 솔루션은 무엇입니까?


실제 Word 문서

"실제"Word 문서를 생성해야하는 경우 Windows 기반 웹 서버와 COM 자동화가 필요합니다. 이 주제에 대한 Joel의 기사적극 권장 합니다.

Word를 속여 원시 HTML을 여는 가짜 HTTP 헤더

다소 일반적인 (그러나 신뢰할 수없는) 대안은 다음과 같습니다.

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"

외부 스타일 시트를 사용하지 마십시오. 모든 것이 같은 파일에 있어야합니다.

이것은 실제 Word 문서를 보내지 않습니다 . 브라우저를 속여서 다운로드로 제공하고 .doc파일 확장자를 기본값으로 설정합니다 . 이전 버전의 Word는 종종 경고 / 보안 메시지없이이 파일을 열고 원시 HTML을 Word로 가져옵니다. 잘못된 Content-Type헤더를 보내는 PHP 는 실제 파일 형식 변환을 구성하지 않습니다.


PHPWord 는 docx 형식으로 Word 문서를 생성 할 수 있습니다. 또한 기존 .docx 파일을 템플릿으로 사용할 수 있습니다. 템플릿 변수는 $ {varname} 형식으로 문서에 추가 할 수 있습니다.

LGPL 라이센스가 있으며 코드와 함께 제공된 예제가 잘 작동했습니다.


OpenOffice 템플릿 + 오픈 오피스 명령 줄 인터페이스.

  1. [% value-to-replace %]와 같은 자리 표시자를 사용하여 ODT 템플릿을 수동으로 만듭니다.
  2. PHP에서 실제 데이터로 템플릿을 인스턴스화 할 때 템플릿 ODT (압축 된 XML)의 압축을 풀고 XML에 대해 실제 값으로 자리 표시 자의 텍스트 대체를 실행합니다.
  3. ODT 다시 압축
  4. OpenOffice 명령 줄 인터페이스를 통해 변환 ODT-> DOC를 실행합니다.

각 단계를 쉽게 수행 할 수있는 도구와 라이브러리가 있습니다.

도움이 될 수 있습니다.


PHP를 사용하여 Linux에서 DOC 파일을 만드는 가장 쉬운 방법은 Zend Framework 구성 요소 phpLiveDocx를 사용하는 것 입니다.

프로젝트 웹 사이트에서 :

"phpLiveDocx를 사용하면 개발자가 PHP의 구조화 된 데이터를 워드 프로세서에서 만든 템플릿과 결합하여 문서를 생성 할 수 있습니다. 결과 문서는 PDF, DOCX, DOC 또는 RTF 파일로 저장할 수 있습니다. 개념은 메일 병합과 동일합니다. . "


OpenTBS 는 템플릿 기술을 사용하여 PHP에서 DOCX 동적 문서를 만들 수 있습니다.

임시 파일이나 명령 줄이 필요하지 않으며 모두 PHP로 제공됩니다.

사진을 추가하거나 삭제할 수 있습니다. 생성 된 문서는 HTML 다운로드, 서버에 저장된 파일 또는 PHP의 바이너리 콘텐츠로 생성 할 수 있습니다.

OpenDocument 파일 (ODT, ODS, ODF 등)을 병합 할 수도 있습니다.

http://www.tinybutstrong.com/opentbs.php


Ivan Krechetov의 답변에 따라 추가 라이브러리없이 docx 및 odt에 대해 메일 병합 (실제로는 단순한 텍스트 바꾸기)을 수행하는 기능이 있습니다.

function mailMerge($templateFile, $newFile, $row)
{
  if (!copy($templateFile, $newFile))  // make a duplicate so we dont overwrite the template
    return false; // could not duplicate template
  $zip = new ZipArchive();
  if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
    return false; // probably not a docx file
  $file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';
  $data = $zip->getFromName($file);
  foreach ($row as $key => $value)
    $data = str_replace($key, $value, $data);
  $zip->deleteName($file);
  $zip->addFromString($file, $data);
  $zip->close();
  return true;
}

그러면 [Person Name]이 Mina로, [Person Last Name]이 Mooo로 바뀝니다.

$replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');
$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');
$templateName = 'personinfo.docx';
if (mailMerge($templateName, $newFile, $replacements))
{
  header('Content-type: application/msword');
  header('Content-Disposition: attachment; filename=' . $templateName);
  header('Accept-Ranges: bytes');
  header('Content-Length: '. filesize($file));
  readfile($newFile);
  unlink($newFile);
}

대체 할 문자열이 너무 일반적인 경우이 함수는 문서를 손상시킬 수 있습니다. [Person Name]과 같은 자세한 대체 문자열을 사용하십시오.


The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.

Another option would be OpenOffice but I can't exactly recommend it since I've never used it.


<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
    {
        $word = new COM("word.application") or die("Unable to instantiate Word");
        //bring it to front
        $word->Visible = 1;
        //open an empty document
        $word->Documents->Add();
        //do some weird stuff
        $word->Selection->TypeText($sFileContent);
        $word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
        //closing word
        $word->Quit();
        //free the object
        $word = null;
        return $sFileName;
    }
?>



<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
 $Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?> 

There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.


Take a look at PHP COM documents (The comments are helpful) http://us3.php.net/com

참고URL : https://stackoverflow.com/questions/124959/create-word-document-using-php-in-linux

반응형