从Laravel导出PDF

时间:2016-11-22 14:58:30

标签: php laravel pdf export export-to-pdf

我正在尝试以PDF格式导出一个表格,但我有一个foreach,我想从foreach中导出所有数据,但并不适用于所有数据,只是为了一行。

以下是代码:

foreach ($posts as $post) {
    $html = '<div class="table-scrollable">
                    <table id="posts" class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Id</th>
                                <th>Name</th>
                                <th>Title</th>
                            </tr>
                        </thead>
                        <tbody id="body"><tr>
                            <td>'
            . $post->id . ' 
                            </td>
                            <td>' .
            $post->name .
            '</td>
                            <td>'
            . $post->title .
            '</td> 
                </tr>
               </tbody>
            </table>
        </div>';
}
return PDF::load($html, 'A4', 'portrait')->download('my_pdf');

1 个答案:

答案 0 :(得分:0)

在foreach构造内部覆盖您的$html变量,您需要在$html之前初始化foreach并使用连接分配.=

$html = '';
foreach ($posts as $post) {
        $html .= '<div class="table-scrollable">
                        <table id="posts" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Name</th>
                                    <th>Title</th>
                                </tr>
                            </thead>
                            <tbody id="body"><tr>
                                <td>'
                . $post->id . ' 
                                </td>
                                <td>' .
                $post->name .
                '</td>
                                <td>'
                . $post->title .
                '</td> 
                    </tr>
                   </tbody>
                </table>
            </div>';
}
return PDF::load($html, 'A4', 'portrait')->download('my_pdf');