簡體   English   中英

在json_decode中獲取null

[英]Getting null in json_decode

我有一個帶有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則可以獲取字符串。

我希望任何人都可以幫助我。

謝謝,E

您無需在調用json_decode之前進行任何解析

$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);

如果仍然為空,則您的JSON可能無效,您可以使用json_last_error進行診斷。

該代碼段有效,因此我認為您的文件解析算法存在問題

<?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);
?>

記錄所示

以適當的PHP類型返回以json編碼的值。 值true,false和null分別返回為TRUE,FALSE和NULL。 如果無法解碼json或編碼的數據深於遞歸限制, 則返回NULL

原因是您沒有有效的JSON

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

您可能是說:

{
    "something": "ss"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM