【问题标题】:json_decode() returns null, even though file_get_contents() works perfectly, even though json is validjson_decode() 返回 null,即使 file_get_contents() 工作正常,即使 json 是有效的
【发布时间】:2019-11-17 00:13:49
【问题描述】:

大家好,我正在使用 php 从 txt 文件中读取一些数据

file_get_contents('../../Datafiles/allThreads.txt');

这将返回以下字符串

[{"OP":"ding","threadName":"","content":"","ID":6}]

当我尝试使用 lint 验证时,我没有任何问题,因此 json 是有效的。

但问题是,当我调用 json_decode 时,它​​一直返回 null:

$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');

为什么会这样?我遵守所有规则?

【问题讨论】:

  • 你必须在json_decode下指定内容,而不是路径

标签: php json jsondecoder


【解决方案1】:

你可以这样做:

//storing json contents in a variable.
$json_contents = file_get_contents('../../Datafiles/allThreads.txt');

//decode json
$currentThreadasList = json_decode($json_contents, TRUE)

编辑-1:

您是否尝试过以下方法:

$currentThreadasList = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);

【讨论】:

  • 哦,是的,我实际上已经这样做了,它只是没有包含在问题中,我的错误
【解决方案2】:

嗯,这段代码

$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');

不起作用,因为json_decode 的第一个参数需要是 JSON 字符串,而不是路径。只需将文件的内容作为参数传递,例如:

$yourJsonDecodedArray = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2018-05-29
    相关资源
    最近更新 更多