Laravel 如何加载视图 blade 并将其与 `DOMDocument` 一起使用?

Laravel how to load a view blade and use it with `DOMDocument`?

在我有多个视图的情况下,在一个循环中我应该将数据传递给那些视图并加载它,之后我需要用 DOMDocument() 解析加载的视图并将它们写入特定的单元格excel。我尝试了以下步骤,但有问题。

 foreach($data as $result_row){
     $result_path = Config::get('auditConfig.result_page.'.$result_row['_type']);
     $view = View::make($result_path, array('item' => $result_row));
     $content = $view->render();

     $doc = new \DOMDocument();
     $doc->preserveWhiteSpace = false;
     $doc->loadHTMLFile($content);
     $table_tr = $doc->getElementsByTagName('tr');
     foreach($table_tr as $n) {
        echo $n->nodeValue;
     }
}

你可以看到函数的定义loadHTMLFile

public bool DOMDocument::loadHTMLFile ( string $filename [, int $options = 0 ] )

第一个参数是$filename,表示要读取的文件路径

在您的情况下,您提供的是视图文件的内容,而不是该视图的文件路径。

假设您的视图为 users.blade.php 那么您将提供如下路径:

$doc->loadHTMLFile(app_path('Views/Users/users.blade.php'));

$viewFile = app_path('Views/Users/users.blade.php'); $doc->loadHTMLFile($viewFile);

因此,您的代码将更改如下

foreach ($data as $result_row) {
    $result_path = Config::get('auditConfig.result_page.' . $result_row['_type']);

    //$view = View::make($result_path, array('item' => $result_row));
    //$content = $view->render();

    $viewFile = app_path($result_path);

    $doc = new \DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->loadHTMLFile($viewFile);
    $table_tr = $doc->getElementsByTagName('tr');

    foreach ($table_tr as $n) {
        echo $n->nodeValue;
    }
}

通过读取字符串。

foreach ($data as $result_row) {
    $result_path = Config::get('auditConfig.result_page.' . $result_row['_type']);

    $view = View::make($result_path, array('item' => $result_row))->__toString();
    //$content = $view->render();

    $viewFile = app_path($result_path);

    $doc = new \DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->loadHTML($view);
    $table_tr = $doc->getElementsByTagName('tr');

    foreach ($table_tr as $n) {
        echo $n->nodeValue;
    }
}