>  기사  >  백엔드 개발  >  PHP에서 DOCX 파일의 텍스트를 읽고 추출하는 방법은 무엇입니까?

PHP에서 DOCX 파일의 텍스트를 읽고 추출하는 방법은 무엇입니까?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-28 17:43:29210검색

How to Read and Extract Text from DOCX Files in PHP?

PHP에서 DOCX 파일 읽기

PHP에서 DOCX 파일을 읽으려고 할 때 출력에 잘못된 문자가 표시되어 사용자가 어려움을 겪을 수 있습니다. 이 문제는 주로 DOCX 파일이 특수한 처리가 필요한 압축 패키지이기 때문에 발생합니다. 다음 코드는 PHP에서 DOCX 파일을 읽고 처리하는 방법을 보여줍니다.

<code class="php">function read_file_docx($filename){

    $striped_content = '';
    $content = '';

    if(!$filename || !file_exists($filename)) return false;

    $zip = zip_open($filename);

    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }// end while

    zip_close($zip);

    //echo $content;
    //echo "<hr>";
    //file_put_contents('1.xml', $content);

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return $striped_content;
}
$filename = "filepath";// or /var/www/html/file.docx

$content = read_file_docx($filename);
if($content !== false) {

    echo nl2br($content);
}
else {
    echo 'Couldn\'t the file. Please check that file.';
}</code>

이 코드는 PHP ZIP 확장을 사용하여 DOCX 파일을 zip 패키지로 엽니다. 그런 다음 문서의 텍스트 콘텐츠가 포함된 zip 패키지 내에서 "word/document.xml" 파일을 찾습니다. 그런 다음 태그를 교체하고 HTML 태그를 제거하여 콘텐츠를 추출하고 정리합니다. 결과 텍스트는 필요에 따라 표시되거나 처리될 수 있습니다.

위 내용은 PHP에서 DOCX 파일의 텍스트를 읽고 추출하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.