首页 > 解决方案 > 使用 Laravel 读取和处理 word 文件

问题描述

我想通过客户端读取上传的 word 文件,使用 laravel 。我正在开发一个在线考试系统,我想让教师能够从 word 文件中导入问题。该文件的内容将包含问题和答案。如果该行包含问号 (?) 我会将这一行视为一个 question ,并且直到下一个问题的后续行将被视为一个答案选项。像这样

what is the capital of USA?
NewYork
*Washington
Texas

what is the Capital of UAE?
DUBAI
*ABU Dhabi
Alriadh

行中有 * 的答案表示这是选项的正确答案。我可以通过上传文本文件来完成所有这些任务。我用这段代码来处理一个文本文件

public function import_text()
    {
        $questions = [];
        $i = 0;
        $questionsFile = fopen( 'test.txt', 'r');
        while ($line = fgets($questionsFile)) {
            if ($line === "\n") {
                $i++;
                continue;
            }
            if (!isset($questions['questions'][$i])){
                $questions['questions'][$i] = [
                    'id' => rand(1596805341210, 9999999999999),
                    'type' => 'Multiple Choice Single Answer',
                    'question' => '',
                    'answer_options' => []
                ];
            }

            if (preg_match("/(.)+\?/", $line)) {
                $questions['questions'][$i]['question'] = $line;
            } else {
                $answer = [
                    'id' => rand(1596805341210, 9999999999999),
                    'marks' => null,
                    'value' => $line,
                    'selected' => false,
                ];
                if (preg_match("/(\*)(.)+/", $line)) {
                   $line= str_replace('*','',$line);
                    $answer['value'] = $line;
                    $answer['marks'] = 100;
                    $answer['selected'] = true;
                }
                $questions['questions'][$i]['answer_options'][] = $answer;
            }
        }
        $data=array();
         
    }

和这样的返回数据

{
  "questions": [
    {
      "id": 9556585048005,
      "type": "Multiple Choice Single Answer",
      "question": "how are you ?\n",
      "answer_options": [
        {
          "id": 2463233296661,
          "marks": 100,
          "value": "Iam good \n",
          "selected": true
        },
        {
          "id": 2918235956978,
          "marks": null,
          "value": "not good \n",
          "selected": false
        }
      ]
    },
    {
      "id": 3438800692307,
      "type": "Multiple Choice Single Answer",
      "question": "what is your name?\n",
      "answer_options": [
        {
          "id": 3338189982867,
          "marks": null,
          "value": "muhaammed\n",
          "selected": false
        },
        {
          "id": 9435683201111,
          "marks": 100,
          "value": "ahmed\n",
          "selected": true
        }
      ]
    }
  ]
}

我想使用 word 文件做同样的事情,如果它包含它,则从 word 文件中获取图像。我找到了库的 phpword 包,但老实说我找不到正确的使用方法。先感谢您

标签: phpjsonlaravelword

解决方案


推荐阅读