【问题标题】:How to save JSON into ini-file with php?如何使用 php 将 JSON 保存到 ini 文件中?
【发布时间】:2023-03-19 21:00:01
【问题描述】:

我有一个 JSON 格式的数据流,我想解析它并将结果保存在 ini 文件中:

{
    "books": [{
        "id": "1",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    }, {
        "id": "2",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    }]
}

这是我的示例数据,我想知道是否有办法将其保存到文件中,无论它是否包含 1 个或多个“id:s”(项目) 我知道如何解析 JSON,但不知道如何将其保存到 ini 格式正确的文件中。

首选格式:

[Books 0]
id= 1
date= 2017-03-12
date_text=sunday 12 march
title= title text

[Books 1]
id"=2
date=2017-03-12
date_text=sunday 12 march
title=title text

【问题讨论】:

标签: php json ini


【解决方案1】:

您可以尝试Zend Config 来完成此任务。打开您的终端并将 zend-config 作为依赖项添加到您的项目中(假设您已经在使用composer):

composer require zendframework/zend-config

现在你可以试试关注了,

$json = <<<JSON
{
    "books": [{
        "id": "1",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    }, {
        "id": "2",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    }]
}
JSON;

$config = new \Zend\Config\Config(json_decode($json, true), true);
$writer = new \Zend\Config\Writer\Ini();
echo $writer->toString($config);

输出将是:

[books]
0.id = "1"
0.date = "2017-03-12"
0.date_text = "sunday 12 march"
0.title = "title text"
1.id = "2"
1.date = "2017-03-12"
1.date_text = "sunday 12 march"
1.title = "title text"

您的 JSON 格式应如下所示,以生成您所写的所需输出:

{
    "books 0": {
        "id": "1",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    },
    "books 1" : {
        "id": "2",
        "date": "2017-03-12",
        "date_text": "sunday 12 march",
        "title": "title text"
    }
}

【讨论】:

  • 试图将 Zend 添加到项目中。除了 phpinfo() 之外,有没有办法知道它是否添加/工作?
  • 您的项目结构/依赖关系与 phpini() 之间没有关系,我建议您在深入了解数据转换之前,先阅读和练习更多的基础知识。
猜你喜欢
  • 2017-08-08
  • 2016-01-25
  • 2015-10-04
  • 2018-01-17
  • 2021-06-25
  • 2012-02-14
  • 2012-05-08
  • 1970-01-01
  • 2013-04-05
相关资源
最近更新 更多