file_get_contents无法打开流:没有错误

时间:2017-08-30 15:43:04

标签: php json file-get-contents

我试图从PHP中的URL获取JSON响应,以便回显它。 但它没有工作,并给我错误代码:

  

... [function.file-get-contents]:无法打开流:...中没有错误

所以我google了一下,发现php.ini中的allow_url_fopen可能已关闭,但在我的情况下,它已打开(我用phpinfo()检查了它。)

我的代码如下:

<?php
   $data = file_get_contents('https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=myapikey');

   echo $data;
 ?>

此网站的正常回复如下:

{
  "status": "ok",
  "source": "bbc-news",
  "sortBy": "top",
  "articles": [
    {
      "author": "BBC News",
      "title": "Houston reels as Storm Harvey bears down on Louisiana",
      "description": "The tropical storm makes landfall in the state after leaving large parts of Houston under water.",
      "url": "http://www.bbc.co.uk/news/world-us-canada-41096565",
      "urlToImage": "https://ichef.bbci.co.uk/images/ic/1024x576/p05dnlwm.jpg",
      "publishedAt": "2017-08-30T14:56:39Z"
    },
    {
      "author": "BBC News",
      "title": "Houston's volunteer navy",
      "description": "Local volunteers are stepping up to help with search and rescue missions in Houston.",
      "url": "http://www.bbc.co.uk/news/av/world-us-canada-41092624/houston-s-volunteer-navy",
      "urlToImage": "https://ichef-1.bbci.co.uk/news/1024/cpsprodpb/A77F/production/_97597824_houston-volunteer_300817_cps-bbc-2.jpg",
      "publishedAt": "2017-08-30T05:23:59Z"
    },
    {
      "author": "BBC News",
      "title": "North Korea: 'Japan missile was first step in Pacific operation'",
      "description": "North Korea says a missile fired over Japan was the \"first step\" in military operations in the Pacific.",
      "url": "http://www.bbc.co.uk/news/world-asia-41091563",
      "urlToImage": "https://ichef.bbci.co.uk/images/ic/1024x576/p05dp42x.jpg",
      "publishedAt": "2017-08-30T06:11:24Z"
    }, ...

我做错了什么?

2 个答案:

答案 0 :(得分:0)

你需要CURL。试试这个。不要忘记包含你的api密钥!您只需修改$url

即可
$url = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top';    
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($ch);

echo($json_response);

答案 1 :(得分:-1)

file_get_contents错误:

传递查询字符串时使用双引号

<?php

  $myapikey = "yourAPIKeyGoesHere";


   $data = file_get_contents("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=$myapikey");

   echo $data;
 ?>

查看代码here

的实时演示