Home  >  Article  >  Backend Development  >  How to use json_encode() in php to turn variables into JSON data

How to use json_encode() in php to turn variables into JSON data

autoload
autoloadOriginal
2021-04-29 14:19:532335browse

How to use json_encode() in php to turn variables into JSON data

JSON is the most common format for data exchange. How to convert variables to JSON format in PHP? This article will take you through how to use phpbuilt-in functionjson_encode() to complete this operation. First, let’s take a look at its syntax structure.

json_encode    ( mixed $value   , int $options = 0   , int $depth = 512   )
  • $value: The $value to be encoded can be any data type except the resource type.

  • $options:JSON constant

  • $depth: Set the maximum depth. Must be greater than 0.

  • Return value: Returns a JSON-encoded string on success or false on failure.

Code example:

<?php
$arr = array (&#39;a&#39;=>"sdf",&#39;b&#39;=>2,&#39;c&#39;=>"dfasd",&#39;d&#39;=>4,&#39;e&#39;=>5);

echo json_encode($arr);
?>
输出:{"a":"sdf","b":2,"c":"dfasd","d":4,"e":5}

Recommendation: 2021 PHP Interview Questions Summary (Collection) 》《php video tutorial

The above is the detailed content of How to use json_encode() in php to turn variables into JSON data. 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