小编典典

从URL获取文件内容?

php

当我在浏览器中使用以下URL时,它将提示我下载带有JSOn内容的文本文件。

https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json

(单击上面的URL查看下载的文件内容)

现在,我想创建一个php页面。我希望当我调用此php页面时,它应调用上述URL并从文件中获取content(json格式)并在屏幕上显示。

我怎样才能做到这一点 ??


阅读 554

收藏
2020-05-29

共1个答案

小编典典

根据您的PHP配置,使用以下命令 可能 很容易:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'));

但是,如果allow_url_fopen未在系统上启用,则可以通过CURL读取数据,如下所示:

<?php
    $curlSession = curl_init();
    curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json');
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

    $jsonData = json_decode(curl_exec($curlSession));
    curl_close($curlSession);
?>

顺便说一句,如果只需要原始JSON数据,则只需删除json_decode

2020-05-29