无法使用php以json格式保存数据到文本文件

时间:2015-05-24 18:04:30

标签: php json file-io

我使用此代码将数据插入文本文件,但无法保存日期 任何帮助请求它可以发布文件.text但没有数据可以保存 无法在" dirdata / formdata.txt"中保存数据

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>​

1 个答案:

答案 0 :(得分:0)

file_put_contents需要完整的服务器路径

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