c#和php文件之间的Json请求
我想将json请求从c#发送到php文件,并将数据保存到文本文件中,但php文件无法读取数据 这是我的密码c#和php文件之间的Json请求,c#,php,json,C#,Php,Json,我想将json请求从c#发送到php文件,并将数据保存到文本文件中,但php文件无法读取数据 这是我的密码 User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", activation = true }; string json = "{\"id\":" + "\"" + user.id + "\""
User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", activation = true };
string json = "{\"id\":" + "\"" + user.id + "\""
+ ",\"name\":" + "\"" + user.name + "\""
+ ",\"address\":" + "\"" + user.address + "\""
+ ",\"activation\":" + "\"" + user.activation + "\"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
和php文件id
<?php
$data = json_decode(file_get_contents('php://input'), true);
$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');
fwrite($handle, $data);
fclose($handle);
echo "SUCCESS";
请问我必须在php文件中做什么才能正确阅读?谢谢这段代码是我解决自己问题所需要的全部:
$_data = json_decode(file_get_contents('php://input'), true);
if (isset($_data)) {
$file = "users.txt";
file_put_contents($file, json_encode($_data));
}
您的$data
是否为空。有json错误吗?您认为如何以任何方式将对象写入文件?您将在LogFile.txt
中只找到对象
或数组
。哦,不要使用字符串连接手动生成JSON。@YeldarKurmangaliyev也是正确的,请参阅