繁体   English   中英

从URL获取文件内容?

[英]Get file content from URL?

当我在浏览器中使用以下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问题+远程网址:
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

不要忘记:要获取HTTPS内容,应在php.ini中启用OPENSSL扩展。 如何获取网站内容使用HTTPS

file_get_contentsjson_decodeecho结合使用。

$url = "https://chart.googleapis....";
$json = file_get_contents($url);

现在你可以回显$ json变量,如果你只想显示输出,或者你可以解码它,并用它做一些事情,如下所示:

$data = json_decode($json);
var_dump($data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM