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
2
  • what do you have tried ? Commented Mar 5, 2017 at 21:00
  • Maybe this could help : PHP array to a .ini file Commented Mar 5, 2017 at 21:04

1 Answer 1

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"
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Trying to get Zend added to Project. is there a way to know if its added/working other than phpinfo() ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.