php json_encode()输出随机跳过字符

时间:2013-02-08 08:06:45

标签: php json output buffered

我在亚马逊ec2实例上使用PHP 5.3.15(cli)(内置:2012年7月20日23:10:20)。当我调用json_encode()时,生成的JSON会随机跳过字符,以使JSON不再有效。即使使用完全相同的参数/数据进行调用,这种情况在某些时候也会发生。奇怪的是它发生在不同的点,随机点,没有模式。在本地MAMP安装中使用相同的数据和相同的代码以及相同版本的PHP不会发生这种情况

  

...“updateTime”:“2012-12-21 03:24:14”,“createTime”:“2012-12-21:”21“,”updateTime“:”2012-12-25 19: 33:25" ,...

你可以在21:“21”看到上面的效果。我甚至不知道从哪里开始解决这个问题。

我已经重新启动,甚至创建了服务器的新虚拟实例。

我非常需要帮助。你能提出的任何建议都会很棒!!

2 个答案:

答案 0 :(得分:1)

你必须为QUOT或其他

设置json encode参数
 $json=json_encode($array,JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);

这是php.net上的json编码样本

 <?php
   $a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

   echo "Normal: ",  json_encode($a), "\n";
   echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
   echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
   echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
   echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
   echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
   echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT |JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

   $b = array();

   echo "Empty array output as array: ", json_encode($b), "\n";
   echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

   $c = array(array(1,2,3));

   echo "Non-associative array output as array: ", json_encode($c), "\n";
   echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

    $d = array('foo' => 'bar', 'baz' => 'long');

   echo "Associative array always output as object: ", json_encode($d), "\n";
   echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
 ?>

输出:

 Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
 Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
 Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
 Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
 Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
 Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
 All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

 Empty array output as array: []
 Empty array output as object: {}

 Non-associative array output as array: [[1,2,3]]
 Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

 Associative array always output as object: {"foo":"bar","baz":"long"}
 Associative array always output as object: {"foo":"bar","baz":"long"}

答案 1 :(得分:0)

我使用代理来分析发生了什么。我正在彼此之后提出两个相同的请求。可能需要注意的是,请求是在objective-c中,而且可能不是php正在破坏,而只是第二个请求取消了第一个请求。