json_decode() returns null,即使 file_get_contents() 完美运行,即使 json 有效
json_decode() returns null, even though file_get_contents() works perfectly, even though json is valid
大家好,我正在使用 php 使用
从 txt 文件中读取一些数据
file_get_contents('../../Datafiles/allThreads.txt');
这个returns下面的字符串
[{"OP":"ding","threadName":"","content":"","ID":6}]
当我尝试使用 lint 验证时,我没有遇到任何问题,因此 json 有效。
但问题是,当我调用 json_decode 时,它一直返回 null:
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
为什么会这样?我遵守所有规则吗?
你可以这样做:
//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);
嗯,这段代码
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
不起作用,因为 json_decode
的第一个参数需要是 JSON 字符串,而不是路径。只需将文件的内容作为参数传递,例如:
$yourJsonDecodedArray = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);
大家好,我正在使用 php 使用
从 txt 文件中读取一些数据file_get_contents('../../Datafiles/allThreads.txt');
这个returns下面的字符串
[{"OP":"ding","threadName":"","content":"","ID":6}]
当我尝试使用 lint 验证时,我没有遇到任何问题,因此 json 有效。
但问题是,当我调用 json_decode 时,它一直返回 null:
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
为什么会这样?我遵守所有规则吗?
你可以这样做:
//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);
嗯,这段代码
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
不起作用,因为 json_decode
的第一个参数需要是 JSON 字符串,而不是路径。只需将文件的内容作为参数传递,例如:
$yourJsonDecodedArray = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);