Awa*_*wan 33 php url file-get-contents
当我在浏览器中使用以下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格式)并在屏幕上显示它.
我怎样才能做到这一点 ??
Joh*_*ker 72
根据您的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'));
Run Code Online (Sandbox Code Playgroud)
但是,如果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);
?>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您只是想要原始JSON数据,那么只需删除json_decode.
T.T*_*dua 19
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
?>
Run Code Online (Sandbox Code Playgroud)
2)更好的方式是CURL:
echo get_remote_data('http://example.com'); // GET request
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request
Run Code Online (Sandbox Code Playgroud)
它自动处理FOLLOWLOCATION问题+远程网址:
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