Php создание файла json

How to Create a JSON File in PHP?

This post will give you example of How to Create Json File in php. This post will give you simple example of How to Generate Json File in php?. I would like to show you php Create Json File and Write. I would like to show you How to Save Json File in php?. Alright, let’s dive into the steps.

There ara two ways to create json file in php. in the first example, we will use fopen(), fwrite() and fclose() to create a json file. in the second example, we will use file_put_contents() to create json file in php.Let’s see both examples with output.

// Create Array for json file

$myArray = [

[ «id» => 1, «name» => «Hardik Savani», «email» => «hardik@gmail.com»], [ «id» => 2, «name» => «Jaydeep Pather», «email» => «jaydeep@gmail.com»], [ «id» => 3, «name» => «Vivek Pather», «email» => «vivek@gmail.com»]

];

// Create new data.json file

$fp = fopen(‘data.json’, ‘w’);

// Write data on json file

fwrite($fp, json_encode($myArray, JSON_PRETTY_PRINT));

// Close json file

fclose($fp);

print(«data.json File created successfully.»);

?>

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[

<

«id»: 1,

«name»: «Hardik Savani»,

«email»: «hardik@gmail.com»

>,

<

«id»: 2,

«name»: «Jaydeep Pather»,

«email»: «jaydeep@gmail.com»

>,

<

«id»: 3,

«name»: «Vivek Pather»,

«email»: «vivek@gmail.com»

>

]

// Create Array for json file

$myArray = [

[ «id» => 1, «name» => «Hardik Savani», «email» => «hardik@gmail.com»], [ «id» => 2, «name» => «Jaydeep Pather», «email» => «jaydeep@gmail.com»], [ «id» => 3, «name» => «Vivek Pather», «email» => «vivek@gmail.com»]

];

// Create json file from array

$data = json_encode($myArray);

file_put_contents(‘data.json’, $data);

print(«data.json File created successfully.»);

?>

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[

<

«id»: 1,

«name»: «Hardik Savani»,

«email»: «hardik@gmail.com»

>,

<

«id»: 2,

«name»: «Jaydeep Pather»,

«email»: «jaydeep@gmail.com»

>,

Читайте также:  Xampp localhost mysql php

<

«id»: 3,

«name»: «Vivek Pather»,

«email»: «vivek@gmail.com»

>

]

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

You might also like.

Источник

Скрипт php для создания json файла, как правильно создать?

Здравствуйте, помогите написать скрипт php с полями ввода для создания json файла, где можно заполнять названия остановок, файл, по требованию ли она и координаты ее, например такого вида:
«routesList»: «440_1»: «name»: «А/С — Водный стадион»,
«stations»: «1»: «coords»:[123,144],
«namest»: «Автостанция»,
«filename»: «as.mp3»
>,
«2»: «coords»:[76,140],
«namest»: «Налоговая»,
«filename»: «nalog.mp3»
>,
«3»: «coords»:[66,345],
«namest»: «Магазин Виктор»,
«filename»: «viktor.mp3»
>,
«4»: «coords»:[55,44],
«namest»: «Кресты»,
«demand»: «true»,
«filename»: «kresty.mp3»
>,
«5»: «coords»:[11,17],
«namest»: «Дубинино»,
«filename»: «dubinino.mp3»
>

>
>,
«21_1»: «name»: «Автостанции — Кривцово»,
«stations»: «1»: «coords»:[123,144],
«namest»: «Автостанция»,
«demand»: «false»,
«filename»: «as.mp3»
>,
«2»: «coords»:[123,144],
«namest»: «Галантерея»,
«demand»: «false»,
«filename»: «as.mp3»
>,
«3»: «coords»:[123,144],
«namest»: «2-я Володарская ул.»,
«demand»: «false»,
«filename»: «as.mp3»
>,
«4»: «coords»:[123,144],
«namest»: «Рабухина»,
«demand»: «true»,
«filename»: «as.mp3»
>,
«5»: «coords»:[123,144],
«namest»: «ул. Горького»,
«demand»: «false»,
«filename»: «as.mp3»
>,
«6»: «coords»:[123,144],
«namest»: «Гараж»,
«demand»: «false»,
«filename»: «as.mp3»
>

Средний 1 комментарий

Источник

Php создание файла json

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Html can body have class

Источник

Generate JSON File in PHP

Generate JSON File in PHP

In this article, we will introduce the method to generate a .json file in PHP.

Use file_put_contents() Function to Generate a .Json File in PHP

The built-in function file_put_contents() could write the content into a file in PHP. It searches for the file to write in, and if the desired file is not present, it creates a new file. We can use this function to create a .json file. The correct syntax to use this function is as follows

file_get_contents($pathOfFile, $info, $customContext, $mode); 

This function returns the number of bytes written on the file if successful and false otherwise.

The below program will create a new .json file and store JSON data into it

php  // data strored in array  $array = Array (  "0" => Array (  "id" => "01",  "name" => "Olivia Mason",  "designation" => "System Architect"  ),  "1" => Array (  "id" => "02",  "name" => "Jennifer Laurence",  "designation" => "Senior Programmer"  ),  "2" => Array (  "id" => "03",  "name" => "Medona Oliver",  "designation" => "Office Manager"  ) );  // encode array to json  $json = json_encode($array); $bytes = file_put_contents("myfile.json", $json); echo "The number of bytes written are $bytes."; ?> 

We use json_encode() function to convert the data stored in the array to a JSON string. Once the data is converted to a JSON string, file_put_contents() function creates a .json file and writes data into it. The output shows the number of bytes, which means the data is written successfully.

The number of bytes written is 207. 

Related Article — PHP JSON

Источник

Оцените статью