无法使用php将数据保存为json格式的文本文件
我使用此代码将数据插入文本文件,但它无法保存日期 任何帮助请求都可以发布文件.text,但不能保存任何数据 无法在“dirdata/formdata.txt”中保存数据 save_json.php无法使用php将数据保存为json格式的文本文件,php,json,file-io,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 = '
<?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
添加iptv频道
添加IPTV频道
类别:
名称:
。
链接:
。
图片:
。
文件内容需要完整的服务器路径
$filetxt = $_SERVER['DOCUMENT_ROOT'].'dirdata/formdata.txt';
我尝试了if(file_put_contents('test/dirdata/formdata.txt',$jsondata)),但没有成功,成功了吗?不大可能发生的如果你不想用我的答案,写下真实的路径。对于像
c:\webserver\my\…
这样的windows,对于像/usr/www/public…
这样的unix,我使用Linux,我上传到var/wwwif的两个文件/var/www
都是www root,那么echo$\u服务器['DOCUMENT\u root']
必须返回/var/www//code>,并且$filetxt将是/var/www/dirdata/formdata.txt假设,您使用windows并将服务器置于c:\web\public
。例如,您在www服务器上有一个文件/dirdata/formdata.txt
。但它的实际路径是c:\web\public\dirdata\formdata.txt
。PHP脚本具有全局变量$\u SERVER['DOCUMENT\u ROOT']
,以了解www根目录的位置。当您使用文件操作功能时,您必须说或c:\web\public\dirdata\formdata.txt
或$\u SERVER['DOCUMENT\u ROOT']./dirdata/formdata.txt
。最后一个更合适。
$filetxt = $_SERVER['DOCUMENT_ROOT'].'dirdata/formdata.txt';