You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel控制器语法错误:意外token '}'问题排查求助

Laravel控制器语法错误:意外的token '}' 解决方法

错误原因

你的代码中importWord方法末尾的闭合大括号前存在全角空格(非标准空白字符),PHP解析器无法识别该字符,因此抛出语法错误。此外还有一个潜在问题:catch块中的Exception未指定全局命名空间,在当前控制器命名空间下会找不到该类。

修正后的代码

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Dompdf\Dompdf;

class WordController extends Controller
{
    public function importForm()
    {
        return view('import');
    }

    public function importWord(Request $request)
    {
        $file_path = $request->file('word_file')->getRealPath();

        try {
            $word = new COM("Word.Application") or die("Unable to instantiate Word");
            $word->Visible = 0;
            $word->Documents->Open($file_path);
            $content = $word->ActiveDocument->Content->Text;
            $word->Quit();
            $word = null;
            unset($word);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred while importing the Word document');
        }

        $dompdf = new Dompdf();
        $dompdf->loadHtml($content);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        return $dompdf->stream();
    }
}

关键修正点

  • 替换importWord方法末尾大括号前的全角空格为半角空格(或直接删除多余空白)
  • 在catch块的Exception前添加\前缀指定全局命名空间,也可在顶部添加use Exception;语句替代

内容的提问来源于stack exchange,提问作者Stack Overflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:16:07