当我在浏览器中使用以下 URL 时,它会提示我下载一个包含 JSOn 内容的文本文件。
https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json
(点击以上网址查看下载文件内容)
现在我想创建一个 php 页面。我希望当我调用此 php 页面时,它应该调用上面的 URL 并从文件中获取内容(json 格式)并将其显示在屏幕上。
我该怎么做??
最佳答案
根据您的 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
。
关于php - 从 URL 获取文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5522636/