FastSitePHP\Encoding\Json

Encode to JSON and decode from JSON.

This classes uses the built-in [json_encode()] and [json_decode()] functions however rather than returning [false] or [null] on errors an exception is thrown.

This class will also create a polyfill function for [json_last_error_msg()] on old versions of PHP if there is an error, and provides compatible code for JSON_BIGINT_AS_STRING when decoding. By default PHP converts large integers to floating-point numbers. When this class is used to decode large ints are converted to strings to prevent data loss.

For most code calling the built-in [json_encode()] and [json_decode()] functions are recommend over this. The main reason to use this class is for JSON_BIGINT_AS_STRING support on old versions of PHP.

Código Fuente

GitHub

Código de Ejemplo

PHP Syntax - Encoding - JSON, Base64, Base64-URL

// Create a Basic Object and Array for Encoding
$object = new \stdClass;
$object->string = 'Test';
$object->number = 123;
$object->bool = true;

$array = [
    'string' => 'Test',
    'number' => 123,
    'bool' => true,
];

// -------------------------------------------
// Encode and Decode JSON
// -------------------------------------------

// Since PHP Array's are used like a Dictionary or Hash, both examples print:
//     {"string":"Test","number":123,"bool":true}
$json = json_encode($object);
echo $json;
echo "\n";

$json = json_encode($array);
echo $json;
echo "\n\n";

// Use the 2nd Parameter for formatted JSON
$json = json_encode($object, JSON_PRETTY_PRINT);
echo $json;
echo "\n";

// Decode and print the object with details using [print_r()]:
$decoded = json_decode($json);
print_r($decoded);
echo "\n";

// By default objects are decoded as [stdClass] objects. To return an array
// instead pass [true] as the 2nd parameter.
$decoded = json_decode($json, true);
print_r($decoded);
echo "\n";

// If there is an error decoding JSON data [null] will be returned.
// If you need to handle invalid JSON you can do so like this:
if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
    throw new \Exception('Error decoding JSON Data: ' . json_last_error_msg());
}

// FastSitePHP includes a JSON helper class which throws exceptions on
// JSON errors instead of the default behavior of returning [false] or [null].
$json = \FastSitePHP\Encoding\Json::encode($object);
$decoded = \FastSitePHP\Encoding\Json::decode($json);

// Often though in most code simply calling [json_encode()] or [json_decode()]
// will be enough. By default, PHP decodes large numbers as floats. If you
// want stricter decoding so they come in strings, then you can use additional
// options. This is how FastSitePHP's JSON class decodes as it is used in the
// JWT, Encryption, and SignedData classes. [JSON_BIGINT_AS_STRING] is not
// avaiable on PHP 5.3 so FastSitePHP uses compatible code.
$decoded = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

// -------------------------------------------
// Encode and Decode Base64
// -------------------------------------------

// Prints: "VGhpcyBpcyBhIHRlc3Q="
$data = 'This is a test';
$base64 = base64_encode($data);
echo $base64;
echo "\n";

// When decoding if there is an error then [false] is returned
$decoded = base64_decode($base64);
print_r($decoded);
echo "\n\n";

// -------------------------------------------
// Encode and Decode Base64-URL Format
// -------------------------------------------

// PHP does not include built-in functions for Base64-URL format so
// FastSitePHP includes a helper class with static methods. They behave
// similar to the built-in functions [base64_encode()]  and [base64_decode()]
// so if there is an error then [false] is returned.

$base64url = \FastSitePHP\Encoding\Base64Url::encode($data);
echo $base64;
echo "\n";

$decoded = \FastSitePHP\Encoding\Base64Url::decode($base64url);
print_r($decoded);
echo "\n";

Métodos

encode($data, $options = null)

Función Estática

Encode data to a JSON String. By default when using PHP 5.4+ JSON_UNESCAPED_UNICODE is used for [$options]. [$options] can be set to any valid value for [json_encode()].

Returns: string

decode($text)

Función Estática

Decode a JSON string back to data. This is equivalent to using the following settings with the built-in function:

    $data = json_decode($text, true, 512, JSON_BIGINT_AS_STRING);

When objects are decoded they are returned as PHP Associative Arrays.

Returns: mixed