Power Engineering
Power Engineering

Reputation: 722

Calculate size in bytes of JSON payload including it in the JSON payload in PHP

I have to send data using JSON in a structure like this:

$JSONDATA= 
    array(
        'response' => true, 
        'error' => null,
        'payload' => 
            array(
                'content' => $content,
                'size' => $size 
                )
        );

NOTE: the variable $content is a dynamic associative array, so its size is not constant. The JSON output is sent using the classical system:

$joutput=json_encode($JSONDATA,JSON_NUMERIC_CHECK);
echo $joutput;

The question is: how can I evaluate the variable $size dynamically and include it in the output?

Upvotes: 6

Views: 11486

Answers (3)

Power Engineering
Power Engineering

Reputation: 722

I guess this will be useful for many others, so I decided to answer to my own question using @mega6382 solution:

// prepare the JSON array 
$JSONDATA= 
array(
    'response' => true, 
    'error' => null,
    'payload' => 
        array(
            'content' => $content,
            'size' => $size 
            )
    );
// evaluate the JSON output size WITHOUT accounting for the size string itself
$t = mb_strlen(json_encode($JSONDATA, JSON_NUMERIC_CHECK), '8bit');
// add the contribution of the size string and update the value
$JSONDATA['payload']['size']=$t+strlen($t);
// output the JSON data
$joutput=json_encode($JSONDATA,JSON_NUMERIC_CHECK);
echo $joutput;

Upvotes: 3

mega6382
mega6382

Reputation: 9396

you can use this to calculate $content's size(DEMO):

$size = strlen(json_encode($content, JSON_NUMERIC_CHECK));

This will provide you with the whole length of json_encode()d string of $content. If you want to calculate the size in bytes(if using multibyte characters), this might be more helpful(DEMO):

$size = mb_strlen(json_encode($content, JSON_NUMERIC_CHECK), '8bit');

Upvotes: 9

Giorgi Lagidze
Giorgi Lagidze

Reputation: 831

Part 1. If this doesn't work for you, I'll update the answer after your next error.

$test_1 = memory_get_usage();
$content = array('key'=>'value');
$size = memory_get_usage() - $test_1;

$JSONDATA= 
    array(
        'response' => true, 
        'error' => null,
        'payload' => 
            array(
                'content' => $content,
                'size' => $size 
                )
        );

Upvotes: 1

Related Questions