下面的代码在php标签中,将{"status":200,"status_message":"details entered in database","data":121}回声输出到提交数据的网页顶部。一切都好!但是我怎么能让它以"any.json"文件的形式返回呢。我经常看到这些出现在Windows7等的网页底部。我已经尝试添加
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
我还尝试了fwrite("yourjson.json",json_encode($response));
但似乎什么都没发生(我在做这件事时评论掉了echo$响应)。如果你有什么建议,我将不胜感激,谢谢你。
<?php
if (isset($_POST['submit']))
{
$fields = array(
'name'=>$_POST['name'],
'email'=>$_POST['email'],
'password'=>$_POST['password'],
'status'=>$_POST['status']
);
$postvars='';
$sep='';
foreach($fields as $key=>$value)
{
$postvars.= $sep.urlencode($key).'='.urlencode($value);
$sep='&';
}
$url = "http://www.anywebpage.com/rest/index.php";
$client = curl_init($url);
curl_setopt($client,CURLOPT_POST,count($fields));
curl_setopt($client, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($client, CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
echo $response;
curl_close($client);
}
?>
上面的代码将数据发送到下面的文件,我也尝试过将文件写入代码,但再次失败。
<?php
$page_title = 'Pass_On';
//process client request (VIA URL)
header("Content = Type:application/json");
//include("function.php");
if (!empty($_POST['name']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$status = $_POST['status'];
require_once('mysqli_connect.php');
$sql = "INSERT INTO usersRest(name, email, password, status) VALUES ( '$name', '$email', '$password', '$status')";
$r = @mysqli_query ($dbc, $sql);
//$qur = mysqli_query($dbc, $sql);
$id = mysqli_insert_id($dbc);
deliver_response(200, "details entered in database", $id);
}
function deliver_response($status,$status_message,$data)
{
header ("HTTP/1.1 $status $status_message");
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']= $data;
$json_response=json_encode($response);
echo $json_response;
}
?>
除了回应,一切都很好。顶部的php代码从同一php文件中的HTML表单接收其值。这只是一个直接的表单提交4个值,名称,电子邮件,密码,状态。
谢谢。
经过一轮搜索,我发现了这段有效的代码。在标题为"Pass_On"的文件末尾使用此项
注释掉//echo$json_response;并添加。。。。。。制作一个名为file1.json的文件它放入该文件中的$json_response变量的内容。
$fp = fopen('file1.json', 'w+');
fwrite($fp, $json_response);
fclose($fp);
然后使用另一个代码部分,即发送数据的顶部代码块。注释掉接近末尾的echo$response,并添加以下代码。
$file = 'file1.json';
file_put_contents($file, $response); //getting this variable, $response, correct was important.
header("Content-type: application/json");
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
curl_close($client);
因此,数据从发送到数据库,如果输入正确,则会将一个名为file1.json的自动json文件返回到发布站点。
希望有一天能帮助到别人。感谢其他投稿人的善意帮助和建议。