PHP code example of suin / json
1. Go to this page and download the library: Download suin/json library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
suin / json example snippets
json_decode(
string $json,
?bool $assoc = false,
?int $depth = 512,
?int $options = 0
): mixed
json_encode(
mixed $value,
?int $options = 0,
?int $depth = 512
): string
\Suin\Json\json_decode(
string $json,
?bool $assoc = false,
?int $depth = 512,
?int $options = 0
): mixed
\Suin\Json\json_encode(
mixed $value,
?int $options = 0,
?int $depth = 512
): string
\Suin\Json::decode(
string $json,
?bool $assoc = false,
?int $depth = 512,
?int $options = 0
): mixed
\Suin\Json::encode(
mixed $value,
?int $options = 0,
?int $depth = 512
): string
use function Suin\Json\json_decode;
use function Suin\Json\json_encode;
// Error handling example
$json = "{'Organization': 'PHP Documentation Team'}";
try {
Json::decode($json);
} catch (Json\DecodingException $e) {
var_dump($e->getMessage());
var_dump($e->getContext()->json());
}
// Output:
// string(35) "Failed to decode JSON: Syntax error"
// string(42) "{'Organization': 'PHP Documentation Team'}"
// preconfigured decoder
$decoder = (new Decoder)->preferArray();
$array1 = $decoder->decode($json1);
$array2 = $decoder->decode($json2); // re-use it
$array3 = $decoder->decode($json3); // re-use it
// preconfigured encoder
$encoder = (new Encoder)->prettyPrint()->unescapeSlashes()->unescapeUnicode();
$json1 = $encoder->encode($value1);
$json2 = $encoder->encode($value2); // re-use it
$json3 = $encoder->encode($value3); // re-use it
use Suin\Json;
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(Json::decode($json));
var_dump(Json::decode($json, true));
// Output:
// object(stdClass)#%d (5) {
// ["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)
// }
use Suin\Json;
$value = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
var_dump(Json::encode($value));
// Output:
// string(31) "{"a":1,"b":2,"c":3,"d":4,"e":5}"