从URL获取文件内容?

49
5个回答

92

根据您的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
谢谢你的投票 :) 编辑:我尝试了不使用json_decode,得到了一个完全呈现的URL,但是使用decode却什么都没有。解码的目的是什么? - user5340092
1
@Steven 它将 JSON 字符串解码为 PHP 变量。 - John Parker
@John_Parker 非常感谢。我目前正在使用Google来渲染URL的快照,但这并不理想,因为图像很小,但是通过将JSON解码为PHP变量,这是一个可以拆分并获取页面标题和第一张图片之类内容的数组吗?谢谢。 - user5340092
1
从PHP 5.1.3开始,BINARYTRANSFER选项无效:当使用CURLOPT_RETURNTRANSFER时,原始输出将始终返回。 https://www.php.net/manual/zh/function.curl-setopt.php - Nadav

25

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


抱歉,我该如何使用REPLACESSOURCES = True进行调用? - Madthew

4

3
使用file_get_contentsjson_decodeecho结合使用。

我正在使用file_get_contents获取内容,但是当我echo它时,它不是JSON格式。它显示了一些特殊字符。 - Awan
@Awan你最终解决了吗?我也看到了特殊字符。 - jewel

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

现在你可以直接输出 $json 变量,如果你只是想显示输出结果,或者你可以对其进行解码,并执行一些操作,例如:
$data = json_decode($json);
var_dump($data);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接