代码之家  ›  专栏  ›  技术社区  ›  Power Engineering

以字节为单位计算JSON负载的大小,包括它在PHP的JSON负载中的大小

  •  1
  • Power Engineering  · 技术社区  · 6 年前

    我必须在这样的结构中使用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并将其包含在输出中?

    3 回复  |  直到 6 年前
        1
  •  1
  •   mega6382    6 年前

    你可以用这个来计算 $content 尺码(尺寸) DEMO ):

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

    这将为您提供 json_encode() D串 美元内容 .如果要以字节为单位计算大小(如果使用多字节字符),这可能更有用( DEMO ):

    $size = mb_strlen(json_encode($content, JSON_NUMERIC_CHECK), '8bit');
    
        2
  •  0
  •   Giorgi Lagidze    6 年前

    第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 
                    )
            );
    
        3
  •  0
  •   Power Engineering    6 年前

    我想这对很多人都有用,所以我决定用@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;