PHP json_encode()

📔 : PHP 🔗

json_encode() function , PHP value को JSON format में encode करता है।

PHP json_encode Syntax

json_encode( mixed $value , $json_constants = '' , int $depth = 512 );
Parameters
  1. mixed $value | required : value जिसे JSON format में convert करना है , आप किसी भी type की value pass कर सकते हैं। लेकिन किसी resource को pass नहीं कर सकते।

    Understanding Resources

    Resources special variables होते हैं , जो किसी external resource को refer करते हैं या कह सकते हैं कि, external resource के reference को hold करते हैं। जैसे file / database resources.

  2. $json_constants | optional : यह JSON Constants , जिसके according value JSON format में convert होती है। कुछ JSON Constants इस प्रकार हैं -

    JSON Contstans
    JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR.

  3. int $depth | optional : यह maximum depth specify करती है , जिसकी value 0 से ज्यादा ही होनी चाहिए।

  4. Return Value : successfully JSON format में convert होने पर json encoded string return होती है , otherwise false return होता है।


PHP json_encode Example

<?php
  $user = ['name'=>'Rahul Kumar', 'age'=> 23, 'gender'=> 'Male'];
  echo json_encode($user);
?> 
Output :
{"name":"Rahul Kumar","age":23,"gender":"Male"}

json_encode() Examples Using Constants

var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
Output
string(4) "12.0" string(2) "12"

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook