php逐行讀取.txt文件內容,並解析每行內容


// 讀取nlp text 並存到mongodb
    public function readNLP(&$errorCode,&$errorMessage)
    {
        try{
// $_SERVER["DOCUMENT_ROOT"],獲取當前運行腳本所在文檔根目錄。$filePath為.txt文件所在路徑
$filePath = $_SERVER["DOCUMENT_ROOT"] . "/checkdata/app/files/nlp.txt"; $file = fopen($filePath, "r"); // 以只讀的方式打開文件 if(empty($file)){ $errorCode = 201; $errorMessage = "file not found"; return; } $i = 0; //輸出文本中所有的行,直到文件結束為止。 while(!feof($file)) { $itemStr = fgets($file); //fgets()函數從文件指針中讀取一行 $itemArray = explode("\t",$itemStr); // 將tab分割的各部分內容提取出來 $itemArray = array_filter($itemArray); // 對itemArray進行校驗 $textDB = new Text(); if($textDB->findItemByText($itemArray[3]) === false){ // 數據庫中不存在該item,insert $addResult = $textDB->addNewItem($itemArray[3],$itemArray[4]); if($addResult === false){ $errorCode = 201; $errorMessage = "insert new item failed"; return "currentIndex: " . $i . " , " . $itemArray[3]; } } ++$i; } fclose($file); }catch (Exception $exception){ $errorCode = $exception->getCode(); $errorMessage = $exception->getMessage(); } return true; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM