dongqindan4406 2018-03-23 17:40
浏览 66
已采纳

使用php从另一个文件读取对象的问题

I have some file called main.config which has:

{"name":"wtf","image":"main.PNG","desc":"This is about this that and that.","tags":{"php","js","html"}}

Now in php I am reading this file and getting its content like this:

$string = "";
$handle = fopen("main.config", "r");
while(!feof($handle)){
  $string .= fgets($handle);
}
fclose($handle);

And now I have been trying to decode this but it always return either null or string with additional "" around.

"{"name":"wtf","image":"main.PNG","desc":"This is about this that and that.","tags":{"php","js","html"}}"

This is everything I tried:

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string), true );
json_decode(preg_replace('/\s+/', '',$string), true);
json_decode(preg_replace('/\x{FEFF}/u', '', $string), true);
json_decode(str_replace('"', '"', $string));
utf8_encode($string); 
stripslashes($string);
trim($string);
html_entity_decode($string);
json_decode(print_r($string, true), true);

But nothing seems to work, is it because I used some different file type or what could it be?

  • 写回答

1条回答 默认 最新

  • douyi1939 2018-03-23 17:54
    关注

    It was just an invalid json formatted string.

    Change to:

    {"name":"wtf","image":"main.PNG","desc":"This is about this that and that.","tags":["php","js","html"]}
    

    You can also read the content with less code using:

    json_decode(file_get_contents('main.config', true);
    

    If you want to validate json format you can use this site also: jsonlint.com

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀