简体   繁体   中英

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. 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

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

first parameter is the $filename that means the path of the file you want to read

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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