雷林鵬分享:PHP JSON

  本章節咱們將爲你們介紹如何使用 PHP 語言來編碼和解碼 JSON 對象。php

  環境配置html

  在 php5.2.0 及以上版本已經內置 JSON 擴展。json

  JSON 函數數組

  函數描述網絡

  json_encode對變量進行 JSON 編碼函數

  json_decode對 JSON 格式的字符串進行解碼,轉換爲 PHP 變量編碼

  json_last_error返回最後發生的錯誤code

  json_encodehtm

  PHP json_encode() 用於對變量進行 JSON 編碼,該函數若是執行成功返回 JSON 數據,不然返回 FALSE 。對象

  語法

  string json_encode ( $value [, $options = 0 ] )

  參數

  value: 要編碼的值。該函數只對 UTF-8 編碼的數據有效。

  options:由如下常量組成的二進制掩碼:JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT

  實例

  如下實例演示瞭如何將 PHP 數組轉換爲 JSON 格式數據:

  

  $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

  echo json_encode($arr);

  ?>

  以上代碼執行結果爲:

  {"a":1,"b":2,"c":3,"d":4,"e":5}

  如下實例演示瞭如何將 PHP 對象轉換爲 JSON 格式數據:

  

  class Emp {

  public $name = "";

  public $hobbies = "";

  public $birthdate = "";

  }

  $e = new Emp();

  $e->name = "sachin";

  $e->hobbies = "sports";

  $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");

  $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

  echo json_encode($e);

  ?>

  以上代碼執行結果爲:

  {"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

  json_decode

  PHP json_decode() 函數用於對 JSON 格式的字符串進行解碼,並轉換爲 PHP 變量。

  語法

  mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

  參數

  json_string: 待解碼的 JSON 字符串,必須是 UTF-8 編碼數據

  assoc: 當該參數爲 TRUE 時,將返回數組,FALSE 時返回對象。

  depth: 整數類型的參數,它指定遞歸深度

  options: 二進制掩碼,目前只支持 JSON_BIGINT_AS_STRING 。

  實例

  如下實例演示瞭如何解碼 JSON 數據:

  

  $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json));

  var_dump(json_decode($json, true));

  ?>

  以上代碼執行結果爲:

  object(stdClass)#1 (5) {

  ["a"] => int(1)

  ["b"] => int(2)

  ["c"] => int(3)

  ["d"] => int(4)

  ["e"] => int(5)

  }

  array(5) {

  ["a"] => int(1)

  ["b"] => int(2)

  ["c"] => int(3)

  ["d"] => int(4)

  ["e"] => int(5)

  }

  點擊查看全部 PHP 教程 文章: https://www.codercto.com/courses/l/5.html(編輯:雷林鵬 來源:網絡 侵刪)

相關文章
相關標籤/搜索