2017-09-04 157 views
0

我被這個問題困住了,我有一個代碼插入數據到數據庫,並且在wordpress頁面查詢它。那麼我想導出它在CSV,但我不知道如何做到這一點。我有在互聯網上找到的代碼,但沒有工作。我不知道爲什麼,請檢查我的代碼。這是我的代碼..

global $wpdb; 
    if(isset($_POST["Export"])){ 
    $result = $wpdb->get_results('SELECT * FROM backend_member', ARRAY_A); 

    header('Content-Type: text/csv'); 
    $date = date("Y-m-d H:i:s"); 
    header('Content-Disposition: attachment;filename=EXPORT_' . $date . '.csv'); 

    foreach ($result as $row) { 
     if ($row) { 
      exportCsv(array_keys($row)); 
     }} 
    while ($row) { 
     foreach ($result as $row) { 
       exportCsv($row); 
     }} 
    function exportCsv($rows) { 
     $separator = ''; 
     foreach ($rows as $row) { 
      echo $separator . $row; 
      $separator = ','; 
     } 
     echo "\r\n"; 
    } 
} 

<div><form class="form-horizontal" action="" enctype="multipart/form-data" method="post" name="upload_excel"> 
<div class="form-group"> 
<div class="col-md-4 col-md-offset-4"><input class="btn btn-success" name="Export" type="submit" value="export to excel" /></div> 
</div> 
</form></div> 

當我點擊導出。我有一個錯誤。

This site can’t be reached 

The webpage at http://www.rimelig-skat.dk/din-admin/ might be temporarily down or it may have moved permanently to a new web address. 
ERR_INVALID_RESPONSE 
+0

你把你的代碼放在哪裏? –

+0

我把代碼放在同一頁面上。 –

+0

@BhumiShah請幫助我:( –

回答

0

下面是更新後的代碼:

global $wpdb; 
if(isset($_POST["Export"])){ 
    $filename = 'test'; 
    $date = date("Y-m-d H:i:s"); 
    $output = fopen('php://output', 'w'); 
    $result = $wpdb->get_results('SELECT * FROM  tp_users', ARRAY_A); 
    fputcsv($output, array('ID', 'Title', ' Date')); 
    foreach ($result as $key => $value) { 
     $modified_values = array(
         $value['ID'], 
         $value['user_login'], 
         $value['user_email'] 
     ); 
     fputcsv($output, $modified_values); 
    } 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: private", false); 
    header('Content-Type: text/csv; charset=utf-8'); 
    // header("Content-Type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=\"" . $filename . " " . $date . ".csv\";"); 
    // header('Content-Disposition: attachment; filename=lunchbox_orders.csv'); 
    header("Content-Transfer-Encoding: binary");exit; 
} 

HTML

<div><form class="form-horizontal" action="" enctype="multipart/form-data" method="post" name="upload_excel"> 

這段代碼完全在我的wordpress工作的罰款。

+0

謝謝你,這是相同的頁面嗎?或者我需要在function.php上添加該代碼?我會嘗試這個。 –

+0

你需要在functions.php中添加動作 –

+0

我是在wordpress上使用小孩主題,需要更新什麼function.php? –

相關問題