목차
php语言中使用json的技巧及json的实现代码详解,json详解
백엔드 개발 PHP 튜토리얼 php语言中使用json的技巧及json的实现代码详解,json详解_PHP教程

php语言中使用json的技巧及json的实现代码详解,json详解_PHP教程

Jul 12, 2016 am 09:06 AM
json php 사용

php语言中使用json的技巧及json的实现代码详解,json详解

目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它。

我写过一篇《数据类型和JSON格式》,探讨它的设计思想。今天,我想总结一下PHP语言对它的支持,这是开发互联网应用程序(特别是编写API)必须了解的知识。

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。

一、json_encode()

该函数主要用来将数组和对象,转换为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}

再看一个对象转换的例子:

$obj->body      = 'another post';
$obj->id       = 21;
$obj->approved    = true;
$obj->favorite_count = 1;
$obj->status     = NULL;
echo json_encode($obj);
로그인 후 복사

结果为

{
    "body":"another post", 
    "id":21,
    "approved":true,
    "favorite_count":1,
    "status":null
}
로그인 후 복사

由于json只接受utf-8编码的字符,所以json_encode()的参数必须是utf-8编码,否则会得到空字符或者null。当中文使用GB2312编码,或者外文使用ISO-8859-1编码的时候,这一点要特别注意。

二、索引数组和关联数组

PHP支持两种数组,一种是只保存"值"(value)的索引数组(indexed array),另一种是保存"名值对"(name/value)的关联数组(associative array)。

由于javascript不支持关联数组,所以json_encode()只将索引数组(indexed array)转为数组格式,而将关联数组(associative array)转为对象格式。

比如,现在有一个索引数组

$arr = Array('one', 'two', 'three');
echo json_encode($arr);
로그인 후 복사

结果为:

["one","two","three"]

如果将它改为关联数组:

$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);
로그인 후 복사

结果就变了:

{"1":"one","2":"two","3":"three"}
로그인 후 복사

注意,数据格式从"[]"(数组)变成了"{}"(对象)。

如果你需要将"索引数组"强制转化成"对象",可以这样写

json_encode( (object)$arr );
로그인 후 복사

或者

json_encode ( $arr, JSON_FORCE_OBJECT );
로그인 후 복사

三、类(class)的转换

下面是一个PHP的类:

class Foo {
    const   ERROR_CODE = '404';
    public  $public_ex = 'this is public';
    private  $private_ex = 'this is private!';
    protected $protected_ex = 'this should be protected';
    public function getErrorCode() {
      return self::ERROR_CODE;
    }
}
로그인 후 복사

现在,对这个类的实例进行json转换:

$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;
로그인 후 복사

输出结果是

{"public_ex":"this is public"}

可以看到,除了公开变量(public),其他东西(常量、私有变量、方法等等)都遗失了。

四、json_decode()

该函数用于将json文本转换为相应的PHP数据结构。下面是一个例子:

$json = '{"foo": 12345}';  
$obj = json_decode($json); 
print $obj->{'foo'}; // 12345
로그인 후 복사

通常情况下,json_decode()总是返回一个PHP对象,而不是数组。比如:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';  
var_dump(json_decode($json));
로그인 후 복사

结果就是生成一个PHP对象:

object(stdClass)#1 (5) {
  
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
  
}
로그인 후 복사

如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));
로그인 후 복사

结果就生成了一个关联数组:

array(5) {
  
     ["a"] => int(1)
     ["b"] => int(2)
     ["c"] => int(3)
     ["d"] => int(4)
     ["e"] => int(5)
  
} 
로그인 후 복사

五、json_decode()的常见错误

下面三种json写法都是错的,你能看出错在哪里吗?

$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';  
$bad_json = '{ "bar": "baz", }';
로그인 후 복사

对这三个字符串执行json_decode()都将返回null,并且报错。

第一个的错误是,json的分隔符(delimiter)只允许使用双引号,不能使用单引号。第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第三个的错误是,最后一个值之后不能添加逗号(trailing comma)。

另外,json只能用来表示对象(object)和数组(array),如果对一个字符串或数值使用json_decode(),将会返回null。

var_dump(json_decode("Hello World")); //null
로그인 후 복사

下面给大家介绍哦php语言的json实现

由于开发一个ajax file manager for web开源项目,数据交换使用的json格式,后来发现在低版本的php上运行会有问题,仔细调试发现json_decode和json_encode无法正常工作,于是查阅资料,发现低版本的php没有实现这两个函数,为了兼容性,我只好自己实现一个php版的json编码解码代码,并保证和json2.js的一致,测试调试并通过,现在将其公布出来,供有相同需求的同学使用:

<&#63;php 
/* * **************************************************************************** 
 * $base: $ 
 * 
 * $Author: $ 
 *   Berlin Qin 
 * 
 * $History: base.js $ 
 *   Berlin Qin  //     created 
 * 
 * $contacted 
 *   webfmt@gmail.com 
 *   www.webfmt.com 
 * 
 * *************************************************************************** */ 
/* =========================================================================== 
 * license 
 * 
 * 、Open Source Licenses 
 * webfmt is distributed under the GPL, LGPL and MPL open source licenses. 
 * This triple copyleft licensing model avoids incompatibility with other open source licenses. 
 * These Open Source licenses are specially indicated for: 
 *  Integrating webfmt into Open Source software; 
 *  Personal and educational use of webfmt; 
 *  Integrating webfmt in commercial software, 
 * taking care of satisfying the Open Source licenses terms, 
 *  while not able or interested on supporting webfmt and its development. 
 * 
 * 、Commercial License – fbis source Closed Distribution License - CDL 
 * For many companies and products, Open Source licenses are not an option. 
 * This is why the fbis source Closed Distribution License (CDL) has been introduced. 
 * It is a non-copyleft license which gives companies complete freedom 
 * when integrating webfmt into their products and web sites. 
 * This license offers a very flexible way to integrate webfmt in your commercial application. 
 * These are the main advantages it offers over an Open Source license: 
 *   Modifications and enhancements doesn't need to be released under an Open Source license; 
 *   There is no need to distribute any Open Source license terms alongside with your product 
 * and no reference to it have to be done; 
 *   No references to webfmt have to be done in any file distributed with your product; 
 *   The source code of webfmt doesn't have to be distributed alongside with your product; 
 *   You can remove any file from webfmt when integrating it with your product. 
 * The CDL is a lifetime license valid for all releases of webfmt published during 
 * and before the year following its purchase. 
 * It's valid for webfmt releases also. It includes year of personal e-mail support. 
 * 
 * ************************************************************************************************************************************************* */ 
function jsonDecode($json) 
{ 
  $result = array(); 
  try 
  { 
    if (PHP_VERSION_ID > ) 
    { 
      $result = (array) json_decode($json); 
    } 
    else 
    { 
      $json = str_replace(array("\\\\", "\\\""), array("&#;", "&#;"), $json); 
      $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
      foreach ($parts as $index => $part) 
      { 
        if (strlen($part) == ) 
        { 
          switch ($part) 
          { 
            case "[": 
            case "{": 
              $parts[$index] = "array("; 
              break; 
            case "]": 
            case "}": 
              $parts[$index] = ")"; 
              break; 
            case ":": 
              $parts[$index] = "=>"; 
              break; 
            case ",": 
              break; 
            default: 
              break; 
          } 
        } 
      } 
      $json = str_replace(array("&#;", "&#;", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts)); 
      $result = eval("return $json;"); 
    } 
  } 
  catch (Exception $e) 
  { 
    $result = array("error" => $e->getCode()); 
  } 
  return $result; 
} 
function valueTostr($val) 
{ 
  if (is_string($val))  
  { 
    $val = str_replace('\"', "\\\"", $val); 
    $val = str_replace("\\", "\\\\", $val); 
    $val = str_replace("/", "\\/", $val); 
    $val = str_replace("\t", "\\t", $val); 
    $val = str_replace("\n", "\\n", $val); 
    $val = str_replace("\r", "\\r", $val); 
    $val = str_replace("\b", "\\b", $val); 
    $val = str_replace("\f", "\\f", $val); 
    return '"' . $val . '"'; 
  } 
  elseif (is_int($val)) 
    return sprintf('%d', $val); 
  elseif (is_float($val)) 
    return sprintf('%F', $val); 
  elseif (is_bool($val)) 
    return ($val &#63; 'true' : 'false'); 
  else 
    return 'null'; 
} 
function jsonEncode($arr) 
{ 
  $result = "{}"; 
  try 
  { 
    if (PHP_VERSION_ID > ) 
    { 
      $result = json_encode($arr); 
    } 
    else 
    { 
      $parts = array(); 
      $is_list = false; 
      if (!is_array($arr)) 
      { 
        $arr = (array) $arr; 
      } 
      $end = count($arr) - ; 
      if (count($arr) > ) 
      { 
        if (is_numeric(key($arr))) 
        { 
          $result = "[";  
          for ($i = ; $i < count($arr); $i++) 
          { 
            if (is_array($arr[$i])) 
            { 
              $result = $result . jsonEncode($arr[$i]); 
            } 
            else 
            { 
              $result = $result . valueTostr($arr[$i]); 
            } 
            if ($i != $end) 
            { 
              $result = $result . ","; 
            } 
          } 
          $result = $result . "]"; 
        } 
        else 
        { 
          $result = "{";  
          $i = ; 
          foreach ($arr as $key => $value) 
          { 
            $result = $result . '"' . $key . '":'; 
            if (is_array($value)) 
            { 
              $result = $result . jsonEncode($value); 
            } 
            else 
            { 
              $result = $result . valueTostr($value); 
            } 
            if ($i != $end) 
            { 
              $result = $result . ","; 
            } 
            $i++; 
          } 
          $result = $result . "}"; 
        } 
      } 
      else 
      { 
        $result = "[]"; 
      } 
    } 
  } 
  catch (Exception $e) 
  { 
  } 
  return $result; 
} 
&#63;> 
로그인 후 복사

如果使用过程有什么问题,可以给我email.欢迎大家指出错误!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1065584.htmlTechArticlephp语言中使用json的技巧及json的实现代码详解,json详解 目前,JSON已经成为最流行的数据交换格式之一,各大网站的API几乎都支持它。 我写...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
2 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
2 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

CakePHP 프로젝트 구성 CakePHP 프로젝트 구성 Sep 10, 2024 pm 05:25 PM

이번 장에서는 CakePHP의 환경 변수, 일반 구성, 데이터베이스 구성, 이메일 구성에 대해 알아봅니다.

Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드 Dec 24, 2024 pm 04:42 PM

PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

CakePHP 날짜 및 시간 CakePHP 날짜 및 시간 Sep 10, 2024 pm 05:27 PM

cakephp4에서 날짜와 시간을 다루기 위해 사용 가능한 FrozenTime 클래스를 활용하겠습니다.

CakePHP 파일 업로드 CakePHP 파일 업로드 Sep 10, 2024 pm 05:27 PM

파일 업로드 작업을 위해 양식 도우미를 사용할 것입니다. 다음은 파일 업로드의 예입니다.

CakePHP 라우팅 CakePHP 라우팅 Sep 10, 2024 pm 05:25 PM

이번 장에서는 라우팅과 관련된 다음과 같은 주제를 학습하겠습니다.

CakePHP 데이터베이스 작업 CakePHP 데이터베이스 작업 Sep 10, 2024 pm 05:25 PM

CakePHP에서 데이터베이스 작업은 매우 쉽습니다. 이번 장에서는 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 이해하겠습니다.

CakePHP 토론 CakePHP 토론 Sep 10, 2024 pm 05:28 PM

CakePHP는 PHP용 오픈 소스 프레임워크입니다. 이는 애플리케이션을 훨씬 쉽게 개발, 배포 및 유지 관리할 수 있도록 하기 위한 것입니다. CakePHP는 강력하고 이해하기 쉬운 MVC와 유사한 아키텍처를 기반으로 합니다. 모델, 뷰 및 컨트롤러 gu

CakePHP 유효성 검사기 만들기 CakePHP 유효성 검사기 만들기 Sep 10, 2024 pm 05:26 PM

컨트롤러에 다음 두 줄을 추가하면 유효성 검사기를 만들 수 있습니다.

See all articles