5

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?

Power Engineering
  • 713
  • 14
  • 26
  • 1
    You can't reliably embed the size of a string in the string *as* a string because that data will change the length of the string and the length of the string will change that data. Use the `Content-Length:` HTTP header instead. – Sammitch Jan 04 '19 at 16:09
  • 1
    it isn't so @Sammitch. See my solution below. – Power Engineering Jan 04 '19 at 16:20

3 Answers3

8

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');
mega6382
  • 9,211
  • 17
  • 48
  • 69
3

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;
Power Engineering
  • 713
  • 14
  • 26
1

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 
                )
        );
Giorgi Lagidze
  • 773
  • 4
  • 24
  • Well Giorgi, I've many thanks for your interesting reply, I've tried it and I get a result but unfortunately the numbers are wrong. In other words if I measure the output using the Chrome inspector I get 664 chars (or bytes) but using your method I get only 227 bytes...any clue? – Power Engineering Jan 04 '19 at 16:09