Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Example2: Another example with a json data and error handling.
<?php
// Data stored in an array called posts
$posts = [
[
"id" => "01",
"title" => "Hello",
],
[
"id" => "02",
"title" => "Yoyo",
],
[
"id" => "03",
"title" => "I like Apples",
]
];
// Encode array to JSON with formatting
$json = json_encode($posts, JSON_PRETTY_PRINT);
// Write JSON to file and handle errors
$file = "myfile.json";
if (file_put_contents($file, $json) !== false) {
echo "Data has been written to $file.";
} else {
echo "Error occurred while writing to $file.";
}
?>
When JSON_PRETTY_PRINT is passed as the second argument to json_encode(), it tells the function to add whitespace and formatting to the generated JSON string. This makes the resulting JSON structure easier to read and understand when viewing it directly.
Example3: With SQL data from a server:
<?php
// Connect to the database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$users = array();
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
// Encode SQL data to JSON
$json = json_encode($users, JSON_PRETTY_PRINT);
// Write JSON to file
$file = "users.json";
if (file_put_contents($file, $json) !== false) {
echo "Data has been written to $file.";
} else {
echo "Error occurred while writing to $file.";
}
} else {
echo "No data found.";
}
// Close the database connection
$conn->close();
?>