当我在浏览器中使用以下URL时,它会提示我下载一个包含JSON内容的文本文件。
https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json
(点击上面的URL查看已下载文件内容)
现在我想创建一个PHP页面。我希望当我调用这个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并从文件中获取内容(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
。
1) 本地最简方法
<?php
echo readfile("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/"); //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled
?>
2) 更好的方法是使用CURL:
echo get_remote_data('http://example.com'); // GET request
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request
它可以自动处理FOLLOWLOCATION问题和远程URL:src="./imageblabla.png"
变成了:src="http://example.com/path/imageblabla.png"
代码: https://github.com/tazotodua/useful-php-scripts/blob/master/get-remote-url-content-data.php
file_get_contents
与json_decode
和echo
结合使用。$url = "https://chart.googleapis....";
$json = file_get_contents($url);
$data = json_decode($json);
var_dump($data);