如何用PHP将JSON保存到ini文件中?

时间:2017-03-05 20:57:54

标签: php json ini

我有一个数据流作为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,而不是如何将它保存为正确格式的文件。

优惠格式:

[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

1 个答案:

答案 0 :(得分: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"
    }
}