Oihana PHP

cbor_encode.php

Table of Contents

Functions

cbor_encode()  : string
Encodes any data into a CBOR binary string.

Functions

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