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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里