[英]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.