我用php获取远程json输出不出来

题目描述

我想通过网站的json获取信息,不知道为什么硬是获取不了,json网址测试了,是正常的,大佬们帮我研究下代码看下有什么问题吗

题目来源及自己的思路

获取数据好像是正常的,自己感觉问题好像出现在$timeline=json_decode($timeline,true);这里唉

相关代码

<?php
function get_file_content($url,$fgc=false){
  $file_contents='';
  if($fgc&&function_exists('file_get_contents')){
    $file_contents=@file_get_contents($url);
  }
  if(empty($file_contents)){
    $ch=curl_init();
    $timeout=5;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $file_contents=curl_exec($ch);
    curl_close($ch);
  }
  return $file_contents;
}

$timeline=get_file_content('这个是json网址');
$timeline=json_decode($timeline,true);
if($timeline){
  $title=$timeline['posts'][0]['title'];
  echo $title;
}else{
  echo(0);
}
?>


阅读 3.2k
4 个回答

报个啥错呀,是json格式错误了吧。

先直接把你获取到的字符串输出。确认是没问题的才行。还有一个是编码是否正确,json只能支持utf8。。。
你可以在json_decode之后,调用json_last_error_msg,来获取最后一次错误信息

error_log打一下log,看看输出的东西对不对。

先打印 $timeline,是正确的json,在json decode之后调用 json_last_error()查看是否存在解析错误。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题