How to generate and obtain JSON files with PHP

不言
Release: 2023-03-29 17:56:02
Original
3395 people have browsed it

This article mainly introduces the method of generating and obtaining JSON files in PHP, involving PHP's operation skills for json format data and files. Friends in need can refer to the following

The examples in this article describe the generation and acquisition of PHP JSON file method. Share it with everyone for your reference, the details are as follows:

First define an array, then traverse the data table, put the corresponding data into the array, and finally convert the array through json_encode()

## The function of the #json_encode() function is to convert numerical values ​​into JSON data storage format.

putjson.php:

<?php
// 生成一个PHP数组
$data = array();
$data[0] = array(&#39;1&#39;,&#39;吴者然&#39;,&#39;onestopweb.cn&#39;);
$data[1] = array(&#39;2&#39;,&#39;何开&#39;,&#39;iteye.com&#39;);
// 把PHP数组转成JSON字符串
$json_string = json_encode($data);
// 写入文件
file_put_contents(&#39;test.json&#39;, $json_string);
?>
Copy after login

If there is a JSON file with the same name, it will be overwritten, if not, it will be created.

The generated or overwritten JSON is as follows:


Copy code The code is as follows:

[["1","\u811A\u672C \u4E4B\u5BB6","www.php.cn"],["2","\u7F16\u7A0B\u5F00\u53D1","php.cn"]]

Then, put the JSON file in The data is read into PHP variables.

getjson.php:

<?php
// 从文件中读取数据到PHP变量
$json_string = file_get_contents(&#39;test.json&#39;);
// 把JSON字符串转成PHP数组
$data = json_decode($json_string, true);
// 显示出来看看
var_dump($data);
echo &#39;<br><br>&#39;;
print_r($data);
echo &#39;<br><br>&#39;;
echo &#39;编号:&#39;.$data[0][0].&#39; 姓名:&#39;.$data[0][1].&#39; 网址:&#39;.$data[0][2];
echo &#39;<br>&#39;;
echo &#39;编号:&#39;.$data[1][0].&#39; 姓名:&#39;.$data[1][1].&#39; 网址:&#39;.$data[1][2];
?>
Copy after login

Rendering:

##Related recommendations:

php generation belt How to implement logo QR code


#

The above is the detailed content of How to generate and obtain JSON files with PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template