2015-06-21 26 views
3

我有這樣如何在PHP中將json文件編寫爲數據源?

"name": "abc", 
"adr": "bcd", 
"partners": { 
      "101": { 
        "name": "xyz.com", 
        "prices": { 
          "1001": { 
          "description": "Single Room", 
          "amount": 125, 
          "from": "2012-10-12", 
          "to": "2012-10-13" 
          }, 
          "1002": { 
          "description": "Double Room", 
          "amount": 139, 
          "from": "2012-10-12", 
          "to": "2012-10-13" 
         } 
        } 

一些數據現在,我必須寫一個JSON與所有這些數據,並用它作爲數據源。

我該怎麼辦?

+0

創建包含你所需要的數據的PHP腳本文件(如數組,對象,什麼),json_encode()將數據轉換爲字符串,然後將該字符串寫入文件 –

+0

@MarkBaker請給出一個小例子 –

+0

除了下面的答案,使用'blob'數據類型爲數據庫中的字段。 – BentCoder

回答

1

您發佈的數據是無效的JSON。它錯過了一些周圍和結束的括號。

好吧,讓我們來解決這個問題......並將其保存爲data.json

{ 
    "name": "abc", 
    "adr": "bcd", 
    "partners": { 
     "101": { 
      "name": "xyz.com", 
      "prices": { 
       "1001": { 
        "description": "SingleRoom", 
        "amount": 125, 
        "from": "2012-10-12", 
        "to": "2012-10-13" 
       }, 
       "1002": { 
        "description": "DoubleRoom", 
        "amount": 139, 
        "from": "2012-10-12", 
        "to": "2012-10-13" 
       } 
      } 
     } 
    } 
} 

要訪問JSON用PHP,你可以簡單地加載文件和JSON轉換爲數組。

<?php 
$jsonFile = "data.json" 
$json = file_get_contents($jsonFile); 
$data = json_decode($json, TRUE); 

echo "<pre>"; 
print_r($data); 
echo "</pre>"; 
?> 
+0

很高興我能幫上忙。 –

0

一個PHP腳本來創建一個包含此數據作爲JSON

// the data you need 
$phpData = [ 
    "name" => "abc", 
    "adr" => "bcd", 
    "partners" => [ 
     "101" => [ 
      "name" => "xyz.com", 
      "prices" => [ 
       "1001" => [ 
        "description" => "Single Room", 
        "amount" => 125, 
        "from" => "2012-10-12", 
        "to" => "2012-10-13", 
       ], 
       "1002" => [ 
        "description" => "Double Room", 
        "amount" => 139, 
        "from" => "2012-10-12", 
        "to" => "2012-10-13", 
       ] 
      ] 
     ] 
    ] 
]; 

// json_encode() that data to a string 
$jsonData = json_encode($phpData); 
// write that string to your file 
file_put_contents('myJsonFile.json', $jsonData); 

,並使用它作爲數據源

$myData = json_decode(
    file_get_contents('myJsonFile.json') 
); 
相關問題