PHP如何将数据写入JSON? [英] php how to write data into json?

查看:844
本文介绍了PHP如何将数据写入JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的php.我想使php页面缓存,从mysql查询数据并将数据存储为json格式.

I am newer for php. I want make php page cache, query data from mysql and store data into json format.

我有很多问题:

  1. 我应该存储哪种类型的文件? .json.txt.cache?因为我还需要使用json解码将数据返回到页面中.

  1. which type of file should I store? .json or .txt or .cache? for I also need use json decode return datas into page.

我想使用cron选项卡,进行许多mysql查询并写入一个json文件.我应该选择哪种写代码? fopen, fwritefile_get_contents或其他命令? (不覆盖数据,而是继续写入.我将删除该文件,并在下一次cron时进行续订)

I want use cron tab, make many mysql queries and write into one json file. what write code should I choose? fopen, fwrite or file_get_contents or other command? (do not cover the data, but continue write. I will deleted the file and renewer it at the next cron time)

如果多次写入json数据(同时10个或更多mysql查询并写入相同的json文件,每个json子格式如{name: ".$row['name']."}),如何完成顶部{和底部}制作标准的json数据格式?

If a multi write into a json data (10 or more mysql query at the same time and write into a same json file, each json child format like {name: ".$row['name']."}), how to completed a top { and bottom } to make a standad json data format?

{////添加方式

{name:.$ row ['name']."}

{name: ".$row['name']."}

{name:.$ row ['name']."}

{name: ".$row['name']."}

//来自另外10个mysql查询的许多名称

// many name from 10 more mysql queries

} //和这个

谢谢.

推荐答案

我应该存储哪种类型的文件

which type of file should I store

没关系.没有固定的扩展名,但是我选择.json只是为了弄清楚文件应该包含什么.

It doesn't matter. There is no fixed extension, but I would pick .json just to make it clear what the file is supposed to contain.

我应该选择哪种写代码?

what write code should I choose?

只需使用 file_put_contents 放置JSON字符串(请参见下一部分)到文件中.

Just use file_put_contents to put the JSON string (see next section) into a file.

每种json子格式,如

each json child format like

真的不想使用该方法.它可能会工作一段时间,但是当您需要处理引用和特殊字符转义之类的内容时,它会变得非常复杂.与其重新发明轮子,不如使用PHP内置的 JSON函数为此.

You really do not want to use that method. It might work for a while, but becomes very complex when you need to handle things like quoting and special-character escapes. Instead of re-inventing the wheel, use PHP's built-in JSON functions for this.

使用PHP的字符串,数字和数组创建所需的数据结构,然后依靠json_encode将其转换为字符串.

Create the data-structure you want using PHP's strings, numbers, and arrays, and then rely on json_encode to turn it into a string.

要注意的主要事情是,根据您的PHP array()的外观,您可能会得到JSON []{}的对比.

The main thing to be careful of is that depending on how your php array() looks, you might get JSON [] versus {}.

这篇关于PHP如何将数据写入JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆