当我在浏览器中使用下面的网址时,它会提示我下载一个包含JSOn内容的文本文件。
https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json
(单击上面的URL查看下载的文件内容)
现在我想创建一个php页面。我希望当我调用这个php页面时,它应该调用上面的URL,并从文件中获取内容(json格式)并将其显示在屏幕上。
我该怎么做呢??
发布于 2011-04-02 18:43:43
根据您的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
即可。
发布于 2013-03-30 01:47:39
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问题+远程urls:
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
发布于 2013-02-18 03:24:46
别忘了:要获取HTTPS内容,应该在php.ini中启用OPENSSL扩展。(how to get contents of site use HTTPS)
https://stackoverflow.com/questions/5522636
复制相似问题