国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) php教程 如何使用 PHP 從 Word、Excel 和 PowerPoint 文件中提取文本?

如何使用 PHP 從 Word、Excel 和 PowerPoint 文件中提取文本?

Nov 17, 2024 pm 07:42 PM

How to Extract Text from Word, Excel, and PowerPoint Files Using PHP?

如何在 PHP 中從 Word 和其他 Office 文件中提取文本

從 Microsoft Office 文檔(包括 Word(.doc 和 . docx)、Excel (.xlsx) 和 PowerPoint (.pptx),通常是在文檔內(nèi)容中搜索等任務(wù)所必需的。

閱讀 Word 文檔

對于.doc 文件,可以使用二進(jìn)制文件方法:

class DocxConversion{
    // ...
    private function read_doc() {
        $fileHandle = fopen($this->filename, "r");
        $line = @fread($fileHandle, filesize($this->filename));   
        $lines = explode(chr(0x0D),$line);
        $outtext = "";
        foreach($lines as $thisline)
          {
            $pos = strpos($thisline, chr(0x00));
            if (($pos !== FALSE)||(strlen($thisline)==0))
              {
              } else {
                $outtext .= $thisline." ";
              }
          }
         $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
        return $outtext;
    }
    // ...
}

對于 .docx 文件(本質(zhì)上是包含 XML 的 zip 文件),您需要:

class DocxConversion{
    // ...
    private function read_docx(){
        $striped_content = '';
        $content = '';
        $zip = zip_open($this->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);
        $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;
    }
    // ...
}

讀取 Excel 文件

這可以通過從 Excel 文件中的“xl/sharedStrings.xml”文件中提取文本來完成:

class DocxConversion{
    // ...
    function xlsx_to_text($input_file){
        $xml_filename = "xl/sharedStrings.xml"; //content file name
        $zip_handle = new ZipArchive;
        $output_text = "";
        if(true === $zip_handle->open($input_file)){
            if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){
                $xml_datas = $zip_handle->getFromIndex($xml_index);
                $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                $output_text = strip_tags($xml_handle->saveXML());
            }else{
                $output_text .="";
            }
            $zip_handle->close();
        }else{
        $output_text .="";
        }
        return $output_text;
    }
    // ...
}

讀取 PowerPoint文件

要從 PowerPoint 演示文稿中提取文本,請打開 zip 容器中的每個幻燈片 (.xml) 文件:

class DocxConversion{
    // ...
    function pptx_to_text($input_file){
        $zip_handle = new ZipArchive;
        $output_text = "";
        if(true === $zip_handle->open($input_file)){
            $slide_number = 1; //loop through slide files
            while(($xml_index = $zip_handle->locateName("ppt/slides/slide".$slide_number.".xml")) !== false){
                $xml_datas = $zip_handle->getFromIndex($xml_index);
                $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
                $output_text .= strip_tags($xml_handle->saveXML());
                $slide_number++;
            }
            if($slide_number == 1){
                $output_text .="";
            }
            $zip_handle->close();
        }else{
        $output_text .="";
        }
        return $output_text;
    }
    // ...
}

用法

要使用此類進(jìn)行文件轉(zhuǎn)換,請使用文件路徑實例化它并調(diào)用convertToText()方法:

$docObj = new DocxConversion("test.doc");
//$docObj = new DocxConversion("test.docx");
//$docObj = new DocxConversion("test.xlsx");
//$docObj = new DocxConversion("test.pptx");
echo $docText= $docObj->convertToText();

以上是如何使用 PHP 從 Word、Excel 和 PowerPoint 文件中提取文本?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Stock Market GPT

Stock Market GPT

人工智能驅(qū)動投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

如何使用PHP中的陣列 如何使用PHP中的陣列 Aug 20, 2025 pm 07:01 PM

phparrayshandledatAcollectionsefefityIndexedorassociativuctures; hearecreatedWithArray()或[],訪問decessedviakeys,modifybyAssignment,iteratifybyAssign,iteratedwithforeach,andManipulationUsfunsionsFunctionsLikeCountLikeCountLikeCountLikeCountLikecount()

描述觀察者的設(shè)計模式及其在PHP中的實現(xiàn)。 描述觀察者的設(shè)計模式及其在PHP中的實現(xiàn)。 Aug 15, 2025 pm 01:54 PM

TheObserverdesignpatternenablesautomaticnotificationofdependentobjectswhenasubject'sstatechanges.1)Itdefinesaone-to-manydependencybetweenobjects;2)Thesubjectmaintainsalistofobserversandnotifiesthemviaacommoninterface;3)Observersimplementanupdatemetho

比較和對比PHP特征,抽象類別和界面與實際用例。 比較和對比PHP特征,抽象類別和界面與實際用例。 Aug 11, 2025 pm 11:17 PM

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

如何在php中使用$ _cookie變量 如何在php中使用$ _cookie變量 Aug 20, 2025 pm 07:00 PM

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag

為MySQL支持的PHP應(yīng)用程序說明數(shù)據(jù)庫索引策略(例如B-Tree,全文)。 為MySQL支持的PHP應(yīng)用程序說明數(shù)據(jù)庫索引策略(例如B-Tree,全文)。 Aug 13, 2025 pm 02:57 PM

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

PHP中有什么公共,私人和保護(hù) PHP中有什么公共,私人和保護(hù) Aug 24, 2025 am 03:29 AM

public成員可被任意訪問;2.private成員僅類內(nèi)可訪問;3.protected成員可在類及子類中訪問;4.合理使用可提升代碼安全與可維護(hù)性。

如何在PHP中執(zhí)行更新查詢 如何在PHP中執(zhí)行更新查詢 Aug 24, 2025 am 05:04 AM

使用MySQLi面向?qū)ο蠓绞剑航⑦B接,預(yù)處理UPDATE語句,綁定參數(shù),執(zhí)行并檢查結(jié)果,最后關(guān)閉資源。2.使用MySQLi過程方式:通過函數(shù)連接數(shù)據(jù)庫,準(zhǔn)備語句,綁定參數(shù),執(zhí)行更新,處理錯誤后關(guān)閉連接。3.使用PDO:通過PDO連接數(shù)據(jù)庫,設(shè)置異常模式,預(yù)處理SQL,綁定參數(shù),執(zhí)行更新,用try-catch處理異常,最后釋放資源。始終使用預(yù)處理語句防止SQL注入,驗證用戶輸入,及時關(guān)閉連接。

如何與PHP中的日期和時間一起工作 如何與PHP中的日期和時間一起工作 Aug 20, 2025 pm 06:57 PM

UnedateTimeFordateSinphp:createWithNewDateTime(),formatwithformat(),modifyviaadd()ormodify(),settimezoneswithdateTimeZone,and compareusingoperatorSordiff()togetIntervals。

See all articles