Oihana PHP

cbor

Table of Contents

Functions

cbor_decode()  : mixed
Decodes a CBOR binary string into a PHP normalized structure (array, scalar, etc.).
cbor_encode()  : string
Encodes any data into a CBOR binary string.

Functions

cbor_decode()

Decodes a CBOR binary string into a PHP normalized structure (array, scalar, etc.).

cbor_decode(string $data[, Closure|null $replacer = null ]) : mixed

This function will attempt to decode CBOR data. If decoding fails due to invalid CBOR content, a RuntimeException will be thrown with an HTTP-style code:

  • 422 (Unprocessable Entity) if the CBOR data is invalid or malformed
  • 500 (Internal Server Error) for unexpected failures
Parameters
$data : string

The binary CBOR data

$replacer : Closure|null = null

Optional callback applied to each decoded value: fn($key, $value)

Tags
throws
RuntimeException

On CBOR decoding failure

example
use function oihana\core\cbor\cbor_decode;

$cbor = "\xA2\x64name\x65Alice\x63age\x18\x1E";
// CBOR encoded map: ['name'=>'Alice','age'=>30]

try
{
    $decoded = cbor_decode($cbor);
    print_r($decoded);
}
catch (RuntimeException $e)
{
    echo "Decoding failed (code {$e->getCode()}): " . $e->getMessage();
}
author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
mixed

The decoded PHP data (array, int, string, etc.)

cbor_encode()

Encodes any data into a CBOR binary string.

cbor_encode(mixed $data[, Closure|null $replacer = null ]) : string

Automatically converts objects and arrays to pure associative arrays.

This function will attempt to convert objects/arrays into associative arrays before encoding. If encoding fails due to invalid data, a RuntimeException will be thrown with an appropriate HTTP-style code:

  • 422 (Unprocessable Entity) if the data cannot be encoded (client-side issue)
  • 500 (Internal Server Error) for unexpected failures (server-side issue)
Parameters
$data : mixed

The data to encode (scalar, array, or object).

$replacer : Closure|null = null

Optional callback applied to each encoded value: fn($key, $value)

Tags
example
use function oihana\core\cbor\cbor_encode;

$data =
[
    'name' => 'Alice',
    'age'  => 30,
    'tags' => ['developer', 'php']
];

try
{
    $cbor = cbor_encode($data);
    echo "CBOR encoded data length: " . strlen($cbor);
}
catch (RuntimeException $e)
{
    echo "Encoding failed (code {$e->getCode()}): " . $e->getMessage();
}
throws
RuntimeException

On CBOR encoding failure.

see
toAssociativeArray()

for details.

author

Marc Alcaraz (ekameleon)

since
1.0.8
Return values
string

The binary CBOR string.


        
On this page

Search results