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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c