CBOR codec extension for PHP
This extension makes it possible to encode/decode CBOR data defined in RFC 8949 on PHP.
This extension itself is not a PHP instance serializer as much as CBOR data format itself is not.
BSD 2-Clause License
phpize
./configure --enable-cbor
make install
See Releases for the Windows binaries.
function cbor_encode(
mixed $value,
int $flags = CBOR_BYTE | CBOR_KEY_BYTE,
?array $options = null,
): string;
function cbor_decode(
string $data,
int $flags = CBOR_BYTE | CBOR_KEY_BYTE,
?array $options = null,
): mixed;
Encodes to or decodes from a CBOR data item.
try {
echo bin2hex(cbor_encode(['binary', 1, 2, null])), "\n";
// 844662696e6172790102f6
var_export(cbor_decode(hex2bin('844662696e6172790102f6')));
// array (
// 0 => 'binary',
// 1 => 1,
// 2 => 2,
// 3 => NULL,
// )
} catch (Cbor\Exception $e) {
echo $e->getMessage(), "\n";
}
When decoding, the CBOR data item must be a single item, or the function will throw an exception with code CBOR_ERROR_EXTRANEOUS_DATA
.
This means this function cannot decode the CBOR sequences format defined in RFC 8742.
See Decoder
class for sequences and progressive decoding.
$options
array elements are:
-
'max_depth'
(default:64
; range:0
..10000
) Maximum number of nesting levels to process. To handle arrays/maps/tags, at least 1 depth is required. -
'max_size'
: (default:65536
; range:0
..0xffffffff
) Decode: Maximum number of elements for array and map to be processed.Depending on the actual limit set by PHP, the value may be lowered.
-
'offset'
(default:0
; range:0
..PHP_INT_MAX
) Decode: Offset of the data to start decoding from. Offset cannot go beyond the length of the data. -
'length'
(default:null
; range:null
|0
..PHP_INT_MAX
) Decode: Length of the data to decode from the offset.null
means the whole remaining data. Length cannot go beyond the available length of the data.Although you cannot decode an empty string,
0
is valid as an option value.
See "Supported Tags" below for the following options:
-
'datetime'
,'bignum'
,'decimal'
:- Encode: default:
true
; values:bool
- Encode: default:
-
'string_ref'
:- Encode: default:
false
; values:bool
|'explicit'
- Decode: default:
true
; values:bool
- Encode: default:
-
'shared_ref'
:- Encode: default:
false
; values:bool
|'unsafe_ref'
- Decode: default:
false
; values:bool
|'shareable'
|'shareable_only'
|'unsafe_ref'
- Encode: default:
Unknown key names are silently ignored.
< 8000 div class="markdown-heading" dir="auto">