Home  >  Article  >  Backend Development  >  How to convert json string to php variable

How to convert json string to php variable

青灯夜游
青灯夜游Original
2021-11-18 18:26:392139browse

In php, you can use the json_decode() function to convert a json string into a PHP variable; this function can be used to decode a JSON string. It accepts a JSON-encoded string and converts it into a PHP variable. , syntax "json_decode($json)".

How to convert json string to php variable

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use the json_decode() function to convert json string to PHP variable.

The json_decode() function can decode strings in JSON format.

Syntax:

json_decode(
    string $json,
    bool $assoc = false,
    int $depth = 512,
    int $options = 0
)

The json_decode() function accepts a JSON encoded string and converts it into a PHP variable

Parameters:

  • json: used to contain the JSON string that needs to be decoded. It only works with UTF-8 encoded strings.

  • assoc: This is a Boolean variable and can be omitted. The default value is false, returning a value of object type; if the value is true, the returned object will be converted to an associative array type.

  • depth: used to indicate the user-specified recursion depth, which can be omitted.

  • options: Binary mask, which can be omitted. The bit masks that can be included are: JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR.

Return value

Returns data encoded in json via the appropriate PHP type. The values ​​true, false and null will return true, false and null accordingly. If json cannot be decoded, or the depth of the encoded data exceeds the recursion limit, null will be returned.

Example:

<?php
$json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

The above routine will output:

How to convert json string to php variable

Recommended learning: "PHP Video Tutorial

The above is the detailed content of How to convert json string to php variable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn