我有一个问题。我有一个PHP代码,可以将数据回显给json对象。 这是我的代码:
<?php
$host = "localhost"; //Your database host server
$db = "..."; //Your database name
$user = "..."; //Your database user
$pass = "..."; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM wedstrijden";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
这是一个.php文件,它回显了JSON对象。但我想要一个显示JSON对象的.json文件(如results.json文件)。这可能吗?
你能帮助我吗?
提前致谢。
答案 0 :(得分:2)
添加json头可能有帮助(在echo片段之前):
header("content-type:application/json");
答案 1 :(得分:1)
使用file_put_contents
函数创建/覆盖文件:
file_put_contents('url/to/your/file/records.json', json_encode($records), LOCK_EX);
从php中读取(输出):
echo file_get_contents('url/to/your/file/records.json');
<强>更新强>
<?php
....
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM wedstrijden";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
$json = json_encode($records);
//NOTE: FOLDERS 'url' and 'file' SHOULD BE WRITABLE WITH PERMISSIONS - 777
//IN CASE 'url' FOLDER PLACED IN SERVER'S ROOT
//IF YOU'RE USING SOME FTP BROWSER CHANGE PERMISSIONS FOR 'url'
//FOLDER AND APPLY IT TO ALL ENCLOSED ITEMS
file_put_contents('url/file/records.json', $json);
}
}
?>
答案 2 :(得分:0)
file_put_contents应该可以解决问题。
答案 3 :(得分:0)
首先,让我们取消MYSQL
演讲。它已被弃用,不应再使用,因此请尝试使用MYSQLI
或其中一个PDO
变体。
其次,听起来你想要一个大的JSON响应。如果是这种情况,请更改此代码:
$query = "SELECT * FROM wedstrijden";
$resultset = mysql_query($query, $connection);
$records = array();
$response = array(); //extra
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
echo json_encode($records)
更像这样的事情:
$query = "SELECT * FROM wedstrijden";
$resultset = mysql_query($query, $connection);
$records = mysql_fetch_all($resultset);
echo json_encode($records, JSON_PRETTY_PRINT);