2015-05-24 89 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 –