Php json encode
From w3cyberlearnings
Contents |
PHP function json_encode
This function convert an array to json data.
Syntax json_encode
- array1: array input
- bitmask(optional): Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE.
array_combine(array1, bitmask);
Example 1
<?php $score = array('a' => 30, 'b' => 20, 'c' => 30, 'x' => 30, 'y' => 32, 'bx' => 20); echo json_encode($score); ?>
Output
{ a: 30, b: 20, c: 30, x: 30, y: 32, bx: 20 }
Example 2
<?php $countries = array('cambodia', 'vietnam', 'thailand', 'lao', 'malaysia', 'indonesia', 'singapore'); echo json_encode($countries,JSON_FORCE_OBJECT); ?>
Output
{ 0: "cambodia", 1: "vietnam", 2: "thailand", 3: "lao", 4: "malaysia", 5: "indonesia", 6: "singapore" }
Example 3
<?php $countries = array('cambodia', 'vietnam', 'thailand', 'lao', 'malaysia', 'indonesia', 'singapore'); echo json_encode($countries); ?>
Output
[ "cambodia", "vietnam", "thailand", "lao", "malaysia", "indonesia", "singapore" ]
Example 4
<?php $a = array('\xa9', 'apple', '<banana>', 'man' => 'boy&girl'); echo "Normal: ", json_encode($a), "<br/>"; echo "Tags: ", json_encode($a, JSON_HEX_TAG), "<br/>"; echo "Apos: ", json_encode($a, JSON_HEX_APOS), "<br/>"; echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "<br/>"; echo "Amp: ", json_encode($a, JSON_HEX_AMP), "<br/>"; ?>
Output
Normal: {"0":"\\xa9","1":"apple","2":"","man":"boy&girl"} Tags: {"0":"\\xa9","1":"apple","2":"\u003Cbanana\u003E","man":"boy&girl"} Apos: {"0":"\\xa9","1":"apple","2":"","man":"boy&girl"} Quot: {"0":"\\xa9","1":"apple","2":"","man":"boy&girl"} Amp: {"0":"\\xa9","1":"apple","2":"","man":"boy\u0026girl"}
Related Links
---json_encode--- json_decode--- json_last_error---