我有一个函数应该将JSON响应返回给客户端,然后继续处理而不锁定客户机,这似乎很好,除非我添加了内容长度头(我希望这样做,以确保客户机被释放)。其职能是:
function replyAndCarryOn($responseText){
ignore_user_abort(true);//stop apache killing php
ob_start();//start buffer output
echo $responseText;
session_write_close();//close session file on server side to avoid blocking other requests
header("Content-Encoding: none");
header('Content-Type: application/json; charset=utf-8');
header("Content-Length: ".ob_get_length());
header("Connection: close");
ob_end_flush();
flush();
}
除了返回给浏览器的JSON字符串由于内容长度错误而被截断外,这很好。例如,下面的字符串
{“结果”:"authList":{"uid":"Adam",“gid”:“用户”,"authid":1},“uid”:“管理”,“gid”:“管理”,"authid":2},{"uid":"George",“gid”:“用户”,"authid":3},{"uid":"test","gid":"Users“:”Users“,"authid":4},”id“:”支付“}
将以下列形式出现:
{“结果”:"authList":{"uid":"Adam",“gid”:“用户”,"authid":1},{“uid”:“管理”,“gid”:“管理”,"authid":2},{"uid":"George",“gid”:“用户”,"authid":3},{"uid":"test","gid":"Users","authid":4},"id":“id”
我可以不使用内容长度头,而apache (2.2)将自动添加‘Transfer-Encoding:“”分块“的标题,这似乎是可行的,但是我想了解为什么ob_get_length不返回我需要的值,我知道如果启用gzip,它可能会产生太长的结果,但是我看到相反的地方,值太短。
所以我想知道:
( a)我在获取内容长度方面做错了什么?
( b)是否存在将其排除在外的问题?
在@Xyv的注释之后,服务器似乎在输出字符串之前输出了一条新行和8个空格,但是这并不包括在ob_get_length返回中。令人尴尬的是,这是一个回车,在第一个php标记之前添加了8个空格。
发布于 2016-01-12 10:40:10
我想为了更好的可读性,我会把这个作为答案。
也许首先捕获输出,然后生成标题,然后是主体?
对我来说,这个例子奏效了:
<?php
function replyAndCarryOn($responseText){
ignore_user_abort(true);//stop apache killing php
ob_flush( );
ob_start( );//start buffer output
echo $responseText;
session_write_close();//close session file on server side to avoid blocking other requests
header("Content-Encoding: none");
header('Content-Type: application/json; charset=utf-8');
header("Content-Length: ".ob_get_length());
header("Connection: close");
echo ob_get_flush();
flush();
}
replyAndCarryOn( '{"result":"AUTH","authList":[{"uid":"Adam","gid":"Users","authid":1}, "uid":"Admin","gid":"Admin","authid":2},{"uid":"George","gid":"Users","authid":3},{"uid":"test","gid":"Users","authid":4}],"id":"Payment"}' );
?>
更新需要知道的是,ob_start()
应该在输出任何实体之前就出现。缓冲区将错过这些数据,因此它可能不会被计算在内。我不是输出缓冲方面的专家,但要确保将ob_start
放在脚本的开头,这样很难(呃)犯任何错误。(因此,在初始<?php
之前要小心地放置空格和/或Tabs )。
https://stackoverflow.com/questions/34740364
复制相似问题