2012-02-14 56 views
0

我正在尋找一個簡單的解決方案,希望有一個簡單的問題。我想有一臺筆記本電腦設置了一個離線html文件,其格式非常簡短,可以提供一個csv文件。我一直在關注fputcsv()這個功能,但我不是最有才華的程序員。如果我有一個簡單的形式,看起來像這樣:在csv文件中存儲脫機HTML表單數據

<?php 
    if(isset($_POST['submit'])) 
    { 
     $myfile = fopen('file.csv', 'w'); 
     fputcsv($myfile, 
      array($_POST['first-name'], $_POST['last-name'], $_POST['email'])); 
     fclose($myfile); 
    } 
?> 

<article role="main"> 

    <header role="banner"> 

     <h1>Email Updates</h1> 

    </header> 

    <section> 

    <form id="form1" name="form1" method="post" action="<?=$_SERVER['PHP_SELF'];?>"> 

     <input type="text" id="first-name" maxlength="100" autocorrect placeholder="First name" /> 
     <input type="text" id="last-name" maxlength="100" autocorrect placeholder="Last name" /> 
     <input type="text" id="email" maxlength="100" autocorrect placeholder="Email address" /> 

     <button type="submit" id="submit" class="oneup">Submit</button> 

    </form> 

    </section> 

</article> 

我需要把它養活一個簡單的csv文件什麼樣的代碼?

回答

0

當這個表單提交,它將填充$ _POST陣列。

所以,你應該添加一些處理提交值的PHP代碼。

例如:

<?php 
    if(isset($_POST['submit'])) 
    { 
     $myfile = fopen('file.csv', 'w'); 
     fputcsv($myfile, 
      array($_POST['first-name'], $_POST['last-name'], $_POST['email'])); 
     fclose($myfile); 
    } 
?> 
+0

我已經添加了PHP的該位爲我的HTML,但我仍然沒有看到任何數據厭煩到文件。 CSV。它取決於我放在哪裏? – blackessej 2012-02-14 18:09:49

+0

通常這會在HTML表單代碼之前。確保你的文件正在被服務器處理爲php;即它有一個.php擴展名,服務器正確識別它。 – JYelton 2012-02-14 18:12:58

+0

是的,所有這些條件都得到滿足。仍然沒有結果。請記住,我在離線存儲php文件,所以它不應該連接到任何服務器... – blackessej 2012-02-14 18:20:24

1

當(如果)在提交表單(正確),這樣做:

if($fp = fopen('file.csv', 'w')) 
{ 
    fputcsv($fp, $_POST); 
} 
fclose($fp); 
0

到djot的答案相似,我會使用這樣的:

if($fp = fopen('file.csv', 'w')){ 
    fputcsv($fp, print_r($_POST, true)); 
} 
fclose($fp); 

注意與真正標誌的print_r,因爲這使得它更可讀。

如果你真的想要把它寫爲CSV,只需使用:

$data = implode(',' $_POST); 
if($fp = fopen('file.csv', 'w')){ 
    fputcsv($fp, $data); 
} 
fclose($fp);