1

I have a datastream as JSON, I want to parse it and want to save result in ini-file :

{
    "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"
    }]
}

This is my sample data and I would like to know if there is a way to save it into a file no matter if it contain 1 or more "id:s" (Items) I know how to parse the JSON but not how to save it down to a file in correct format for an ini.

Preferable format:

[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
Vijay Verma
  • 3,660
  • 2
  • 19
  • 27
Kr4k4n
  • 51
  • 2
  • 8

1 Answers1

1

You can try Zend Config for this task. Open your terminal and add zend-config to your project as dependency (assuming you already using composer):

composer require zendframework/zend-config

Now you can try following,

$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);

The output will be:

[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"

Your JSON format should be look like below to produce desired output you wrote in question:

{
    "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"
    }
}
edigu
  • 9,878
  • 5
  • 57
  • 80
  • Trying to get Zend added to Project. is there a way to know if its added/working other than phpinfo() ? – Kr4k4n Mar 05 '17 at 22:24
  • There is no relation between your project structure/dependencies and phpini() I would recommend grasping the basics first by reading & practicing more before diving into data transformation. – edigu Nov 03 '18 at 12:27