2015-05-24 139 views
0

我使用此代碼插入數據到文本文件,但它提供無法保存日期 任何幫助請求它可以發佈文件.text但沒有數據可以保存 無法將數據保存在 「dirdata/formdata.txt」無法保存數據到文本文件使用PHP保存爲JSON格式

save_json.php

<?php 
// Append new form data in json string saved in text file 
// From: http://coursesweb.net/php-mysql/ 

// path and name of the file 
$filetxt = 'dirdata/formdata.txt'; 

// check if all form data are submited, else output error message 
     if(isset($_POST['category']) && isset($_POST['name']) && isset($_POST['link']) && isset($_POST['pic'])) { 
    // if form fields are empty, outputs message, else, gets their data 
     if(empty($_POST['category']) || empty($_POST['name']) || empty($_POST['link']) || empty($_POST['pic'])) {     
    echo 'All fields are required'; 
    } 
    else { 
    // gets and adds form data into an array 
    $formdata = array(
     'category'=> (float) $_POST['category'], 
      'name'=> (float) $_POST['name'], 
      'link'=> (float) $_POST['link'], 
      'pic'=> (float) $_POST['pic'], 
    ); 

    // path and name of the file 
    $filetxt = 'dirdata/formdata.txt'; 

    $arr_data = array();  // to store all form data 

    // check if the file exists 
    if(file_exists($filetxt)) { 
     // gets json-data from file 
     $jsondata = file_get_contents($filetxt); 

     // converts json string into array 
     $arr_data = json_decode($jsondata, true); 
    } 

    // appends the array with new form data 
    $arr_data[] = $formdata; 

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable) 
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT); 

    // saves the json string in "formdata.txt" (in "dirdata" folder) 
    // outputs error message if data cannot be saved 
    if(file_put_contents('dirdata/formdata.txt',$jsondata)) echo 'Data successfully saved'; 
    else echo 'Unable to save data in "dirdata/formdata.txt"'; 
    } 
} 
else echo 'Form fields not submited'; 
?> 

​ 

的index.html

<form action="save_json.php" method="post"><br><br><br><br> 
<head> 
<title>Add iptv channel</title> 
</head> 
<center><body> 
ADD IPTV CHANNEL 
</body></center><br><br> 

<center>category: <input type="text" name="category" id="category" SIZE="100" MAXLENGTH="40"/></br>.</center><br> 

<center>name: <input type="text" name="name" id="name" SIZE="100" MAXLENGTH="40"/></br><br>.</center> 

<center>link: <input type="text" name="link" id="link"SIZE="100" MAXLENGTH="40" /></br><br>.</center> 

<center>pic: <input type="text" name="pic" id="pic" SIZE="100" MAXLENGTH="40"/></br><br>.</center> 

<center><input type="submit" id="submit" value="Submit" /></center>​ 

回答

0

file_put_contents需要完整的服務器路徑

$filetxt = $_SERVER['DOCUMENT_ROOT'].'dirdata/formdata.txt'; 
+0

我 嘗試,如果(file_put_contents( '測試/ dirdata/formdata.txt',$ jsondata))不是成功 –

+0

成功是什麼呢?不太可能。如果你不知何故不想使用我的答案,請寫出真實的路徑。對於像'c:\ webserver \ my \ ...'這樣的窗口,對於像'/ usr/www/public這樣的unix \'。' – splash58

+0

我使用Linux和這兩個文件我上傳到var/www –