2016-11-22 50 views
0

我想導出PDF格式的表格,但我有一個foreach,我想從foreach中導出所有數據,但不適用於所有,僅適用於一行。從Laravel導出PDF

下面是代碼:

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'); 
+4

結束串到HTML在每次迭代中,您都會覆蓋'$ html'。你可能想追加它,對吧? –

+0

是的,但我不知道如何。 – Sulde1985

+0

請閱讀http://php.net/manual/en/language.operators.string.php瞭解有關字符串運算符的內容 –

回答

0

內部foreach構造你重寫你的$html變量,需要foreach之前初始化$html並添加使用連接賦值.=

$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'); 
+0

感謝您的回答,但這就是我正在做的,我得到這個錯誤」本地主機頁面不工作 本地主機當前無法處理此請求。「 – Sulde1985

+0

我有太多的數據,這是問題,但解決方案是好的。感謝所有人的幫助。 – Sulde1985