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; }