To create a JSON file in PHP, we need to follow these steps:
json_encode()
function to encode the array into a JSON string.fopen()
function in write mode. You can choose any desired filename and path.fwrite()
function.fclose()
function.Here's the code to accomplish this:
main.php264 chars16 lines
In this example, we are creating an array named $data
with some sample data. We are then using the json_encode()
function to encode this array into a JSON string.
We are then using the fopen()
function to open a file named example.json
in write mode. The fwrite()
function is used to write the JSON string to the file, and then we close the file using the fclose()
function.
Finally, we print a success message to the screen.
Note: Make sure the web server has write permission to the directory(folder) where the file is being created.
gistlibby LogSnag