Home > php教程 > PHP开发 > body text

php json function usage

高洛峰
Release: 2016-11-29 15:58:23
Original
1070 people have browsed it

Today I submitted a JSON data to PHP using POST method (pay attention to GET method too), for example:

{"a":1,"b":2}

Retrieve this data in PHP: $s=$ _POST['data'] ;//or $_GET['data'], then this string is escaped after being taken out: {"a":1,"b":2}

If called directly:

$obj = json_decode($s);

print_r($obj);

echo $obj->a;

is wrong and an error will be reported. If $s is directly defined: $s='{"a ":1,"b":2}'; then there is no problem. Therefore, when processing JSON in PHP, you need to perform some escaping processing: $s=strips tutorial lashes($_POST['data']); Then proceed to json Just decode it.

json_decode — Encode JSON formatted strings

json_encode — JSON encode variables

Report a bug parameter

value

The value to be encoded can be any data type except resource type. This function can only accept UTF-8 encoded data (Translation: refers to character/string type data)

Report a bug Return value

If the encoding is successful, a string represented in JSON form will be returned.

Report a bug Example

Example #1 A json_encode() example, the code is as follows:

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

echo json_encode($arr);

?>

//The above routine will output :

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

json_encode — JSON encoding of variables

json_decode — JSON format The string is encoded

Report a bug Description

mixed json_decode ( string $json [, bool $assoc ] )

Accepts a JSON format string and converts it into a PHP variable

Report a bug Parameters

json

A string in json string format to be decoded.

assoc

When this parameter is TRUE, array will be returned instead of object.

Report a bug Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.

Report a bug Example

Example #1 Example of json_decode()

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

var_dump(json_decode($json) ; 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)

}

*/

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!