2016年6月13日 星期一

利用 PHP 建立或讀取 JSON 資料

PHP 直接有寫好函式庫可以處理 JSON 字串,就是利用 json_encode json_decode

範例:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
$cart = array(
  "orderID" => 12345,
  "shopperName" => "John Smith",
  "shopperEmail" => "johnsmith@example.com",
  "contents" => array(
    array(
      "productID" => 34,
      "productName" => "SuperWidget",
      "quantity" => 1
    ),
    array(
      "productID" => 56,
      "productName" => "WonderWidget",
      "quantity" => 3
    )
  ),
  "orderCompleted" => true
);
echo json_encode( $cart );
?>
輸出
01
{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com","contents":[{"productID":34,"productName":"SuperWidget","quantity":1},{"productID":56,"productName":"WonderWidget","quantity":3}],"orderCompleted":true}
只要用 array 方式將資料輸出,再透過 json_encode 就可以了

接下來看看底下 PHP 如何讀取 JSON 字串
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
$jsonString = '
{                                          
  "orderID": 12345,                        
  "shopperName": "John Smith",             
  "shopperEmail": "johnsmith@example.com"
  "contents": [                            
    {                                      
      "productID": 34,                     
      "productName": "SuperWidget",        
      "quantity": 1                       
    },                                     
    {                                      
      "productID": 56,                     
      "productName": "WonderWidget",       
      "quantity": 3                        
    }                                      
  ],                                       
  "orderCompleted": true                   
}                                          
';
$cart = json_decode( $jsonString );
echo $cart->shopperEmail . "<br>";
echo $cart->contents[1]->productName . "<br>";
?>

沒有留言:

張貼留言