2017-03-05 60 views
0

我有一個數據流爲JSON,我想分析它,並要保存導致ini文件:如何使用php將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」(Items) 我知道如何解析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 
+0

你有什麼試過的? – hassan

+0

也許這可能有助於:[PHP數組到.ini文件](http://stackoverflow.com/questions/17316873/php-array-to-a-ini-file/17317168#17317168) – JazZ

回答

0

您可以嘗試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" 
    } 
} 
+0

試圖讓Zend增加項目。有沒有辦法知道它是否添加/工作,而不是phpinfo()? – Kr4k4n

相關問題