[英]output a json file response instead of an echo response in php
下面的代码在php标记内,在提交数据的网页顶部回显了{“ status”:200,“ status_message”:“在数据库中输入的详细信息”,“ data”:121}。 一切都很好! 但是我怎样才能将其作为“ any.json”文件返回。 我经常看到这些内容出现在Windows 7等网页的底部。我尝试添加
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
我也尝试了fwrite(“ yourjson.json”,json_encode($ response));
但似乎没有任何反应(执行此操作时,我将echo $ response注释掉了)。 如果您有任何建议,我将非常感谢,谢谢。
<?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表单接收其值。 这是直接提交四个值的表格,名称,电子邮件,密码,状态。
谢谢。
经过一轮搜索后,我发现此代码有效。 在标题为“ 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文件返回到发布站点。
希望有帮助的人。 感谢其他贡献者的友好帮助和建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.