PHP json_encode在json-string的开头添加了一些数字(十六进制?)

时间:2012-12-08 10:26:19

标签: php json fsockopen

我将json_encoded数据从一个php脚本回显到另一个(该请求由fsockopen / GET发出)。

编码包含40个元素的数组时,没有问题。当用41执行完全相同的操作时,一些数字和\ r \ n被添加到json字符串的开头。

这是我回应它之前的字符串的开头:

{"transactions":[{"transaction_id":"03U191739F337671L",

这是我发送数据的方式:

header('Content-Type: text/plain; charset=utf-8');
error_log(json_encode($transaction_list));
echo json_encode($transaction_list);

我收到请求脚本中的数据后,我再次将其打印到error_log:

27fc\r\n{"transactions":[{"transaction_id":"03U191739F337671L",

如果我检索的数据较少,则“27fc \ r \ n”不存在。

这是我处理响应的方式:

$response="";
 while (!feof($fp)) {
            $response .= fgets($fp, 128);
 }

 //Seperate header and content
 $separator_position = strpos($response,"\r\n\r\n");      

 $header_text = substr($response,0,$separator_position);      

 $body = substr($response,$separator_position+4);                   
 error_log($body);  

 fclose($fp);   

我试过玩fsockopen请求的时间,这没关系。与php.ini中的max_execution_time和max_input_time相同的事情并不重要。我认为由于超时,某些方面的内容可能会被削减......

第41个阵列的内容格式与前面的格式不同。

发生了什么,我该如何解决?

我正在使用Linux,Apache(httpd)和PHP。

更新

数据似乎是分块的。在响应中,包括以下标题:“Transfer-Encoding:chunked”。

1 个答案:

答案 0 :(得分:0)

基于@Salmans使用file_get_contents的想法,这是可行的解决方案。这使用POST发送数据(GET似乎没有工作,我认为必须将查询字符串附加到URL自己):

$postdata = http_build_query(         
   array('customer_id' => $customer_id)
);

$opts = array('http' =>
   array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata
   )
);

$context  = stream_context_create($opts);  
$content = file_get_contents($my_url, false, $context);
return $content;