简体   繁体   English

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

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

In a case I have multiple views, and in a loop I should pass data to those view and load it, after that I need to parse the loaded view with DOMDocument() and write those to specific cell of excel. 在一个情况下,我有多个视图,并且在循环中,我应该将数据传递给那些视图并加载它,之后,我需要使用DOMDocument()解析加载的视图并将其写入excel的特定单元格。 I have tried bellow steps, but has problem. 我已经尝试了下面的步骤,但是有问题。

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

As you can see the definition of the function loadHTMLFile 如您所见,函数loadHTMLFile的定义

public bool DOMDocument::loadHTMLFile ( string $filename [, int $options = 0 ] ) 公共布尔DOMDocument :: loadHTMLFile(字符串$ filename [,int $ options = 0])

first parameter is the $filename that means the path of the file you want to read 第一个参数是$filename ,表示您要读取的文件的路径

In your case you are providing the content of the view file instead of the file path of that view. 在您的情况下,您要提供视图文件的内容,而不是该视图的文件路径。

Let's say you have view as users.blade.php then you will provide the path as follow: 假设您以users.blade.php的身份查看,然后提供以下路径:

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

OR 要么

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

So as per this your code will be change as follow 因此,根据此代码,您的代码将如下更改

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

By reading as string. 通过读取为字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM