在json_decode中获取null

时间:2015-05-14 08:17:32

标签: javascript php arrays json

我有一个文本文件,上面有json。以下示例:

{'something' : 'ss'}

我正在尝试在php上阅读它并使用json_decode将其转换为数组。

        $temp = '';
        $fh = fopen( '/quiz' . $testid . '.txt' ,'r');

        while ($line = fgets($fh)) {
            $temp .= $line;
        }
        fclose($fh);

        $temp = str_replace("\n","",$temp); //to remove new line
        $temp = str_replace("\r","",$temp);
        $temp = json_decode($temp);

但是我得到了null

如果我没有json_decode它......我可以得到字符串。

我希望有人能帮助我。

谢谢, ë

3 个答案:

答案 0 :(得分:1)

在调用json_decode

之前,您无需进行任何解析
$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);

如果您仍然无效,那么您的JSON可能无效,您可以使用json_last_error进行诊断。

答案 1 :(得分:0)

此代码段可行,因此我认为您的文件解析算法存在问题

<?php
$temp = '';

$temp='{
"a":1,
"b":[1,2,3]
}';

$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
var_dump($temp);
?>

答案 2 :(得分:0)

作为documented

  

以适当的PHP类型返回json中编码的值。值   true,false和null返回为TRUE,FALSE和NULL   分别。 如果json无法解码,则返回NULL 或者   编码数据比递归限制更深。

原因是您没有valid JSON

Parse error on line 1:
{    'something': 'ss'}
-----^
Expecting 'STRING', '}'

你可能意味着:

{
    "something": "ss"
}