计算JSON有效负载的大小(以字节为单位),包括在PHP的JSON有效负载中 [英] Calculate size in bytes of JSON payload including it in the JSON payload in PHP
问题描述
我必须使用JSON这样的结构发送数据:
I have to send data using JSON in a structure like this:
$JSONDATA=
array(
'response' => true,
'error' => null,
'payload' =>
array(
'content' => $content,
'size' => $size
)
);
注意:变量$ content是一个动态关联数组,因此其大小不是恒定的. JSON输出使用经典系统发送:
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;
问题是:如何动态评估变量$ size并将其包含在输出中?
The question is: how can I evaluate the variable $size dynamically and include it in the output?
推荐答案
you can use this to calculate $content
's size(DEMO):
$size = strlen(json_encode($content, JSON_NUMERIC_CHECK));
这将为您提供json_encode()
d字符串$content
的整个长度.如果要以字节为单位计算大小(如果使用多字节字符),则可能会更有用( DEMO ) :
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');
这篇关于计算JSON有效负载的大小(以字节为单位),包括在PHP的JSON有效负载中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!