计算 JSON 有效负载的字节大小,包括在 PHP 中的 JSON 有效负载中

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

我必须在这样的结构中使用 JSON 发送数据:

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

注意:变量$content 是一个动态关联数组,所以它的大小不是常量。 JSON输出使用经典系统发送:

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

问题是:如何动态计算变量 $size 并将其包含在输出中?

第 1 部分。如果这对您不起作用,我会在您下次出错后更新答案。

$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 
                )
        );

您可以使用它来计算 $content 的大小 (DEMO):

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

这将为您提供 $contentjson_encode()d 字符串的全长。如果您想以字节为单位计算大小(如果使用多字节字符),这可能更有帮助(DEMO):

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

我想这对其他很多人都有用,所以我决定使用@mega6382 解决方案来回答我自己的问题:

// 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;