PHP获取URL或页面的内容

13

我正在尝试创建一个PHP脚本,可以请求来自外部服务器的数据,比如HTML内容,然后对收到的内容进行一些处理。以下是我尝试实现的一个通用示例:

//Get the HTML generated by http://api.somesite.com/

//Now tack on the Unix timestamp of when the data was received
$myFetchedData = $dataFromExternalServer . "\n Data received at: ". time();

echo $myFetchedData;

我在想我应该在这里使用curl,但之后我不确定。请问有人能够发布一个通用的例子,告诉我如何做到这一点吗?


可能是重复的问题:如何在PHP中获取网页的HTML代码? - Cees Timmerman
6个回答

36

如果您只需要使用 GET 方法,且您的服务器启用了 allow_url_fopen,您可以简单地使用以下代码:

$data = file_get_contents('http://api.somesite.com');

Curl 也可能缺失。因此,您可能希望使用任何可用的工具。 - ThiefMaster
@Ascherer 实际上,我认为cURL更好。它似乎具有更好的性能。http://stackoverflow.com/questions/555523/file-get-contents-vs-curl-what-has-better-performance。 - tyronegcarter
为了速度,但不是简单性。 - Ascherer
如果可以选择,我会选择cURL。你可以获得更多的控制权(如果你需要使用它),并且它具有更强大的错误处理能力。如果你正在加载页面时进行GET请求,你需要确保处理GET请求所需的时间非常长或失败的情况。 - Eli
file_get_contents在许多服务器上被禁用,因为许多恶意攻击都是通过它进行的。更好的选择是使用下一个答案中建议的cURL方法。 - David
显示剩余3条评论

10

以下是如何使用cURL从远程URL获取内容的方法。您需要定义函数并进行调用,例如url_get_contents("http://example.com/")

function url_get_contents($url, $useragent='cURL', $headers=false, $follow_redirects=true, $debug=false) {

    // initialise the CURL library
    $ch = curl_init();

    // specify the URL to be retrieved
    curl_setopt($ch, CURLOPT_URL,$url);

    // we want to get the contents of the URL and store it in a variable
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

    // specify the useragent: this is a required courtesy to site owners
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

    // ignore SSL errors
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // return headers as requested
    if ($headers==true){
        curl_setopt($ch, CURLOPT_HEADER,1);
    }

    // only return headers
    if ($headers=='headers only') {
        curl_setopt($ch, CURLOPT_NOBODY ,1);
    }

    // follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
    if ($follow_redirects==true) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    }

    // if debugging, return an array with CURL's debug info and the URL contents
    if ($debug==true) {
        $result['contents']=curl_exec($ch);
        $result['info']=curl_getinfo($ch);
    }

    // otherwise just return the contents as a variable
    else $result=curl_exec($ch);

    // free resources
    curl_close($ch);

    // send back the data
    return $result;
}

6

简单方法

<?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
?> 

最佳方案(使用cURL):

echo get_remote_data('http://example.com');   //SIMPLE REQUEST;
//OR
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); //POST REQUEST;

(CODE: at GitHub )


1
请不要进行这种编辑,@solutioner。最好将此帖标记为重复。 - Lix
仅包含链接的答案不被认为是[so]的好答案。 - Lix
根据http://php.net/manual/en/function.include.php,似乎从一个包含文件中输出返回值并不能像你所意味的那样起到作用。 - Beachhouse

6
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.url.com/cakephp/controller/action/param:1" ); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); 
$dataFromExternalServer=curl_exec($ch); 

参见: http://php.net/manual/zh/function.curl-exec.php


1

简单来说:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.somesite.com/');
$dataFromExternalServer = curl_exec($ch);

1
你需要使用 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );,否则返回的数据将被发送到客户端。 - ThiefMaster
当然可以,还有许多其他的curl选项可以设置。我只是说“简单地说”。 - Datajam

0
如果你的PHP安装不支持curl且不支持allow_url_fopen,那么如果你安装了PECL,这里有一个选择:
$body = http_parse_message(http_get($url))->body;

2
(PECL pecl_http >= 0.1.0)- 比curl或allow_url_fopen更不可能 - ThiefMaster
我的主机有PECL,但我同意,这可能更像是一个冒险。 - Håvard S
我同意,我希望能够获得最大的兼容性。不过还是谢谢你,Håvard! - Oliver Spryn

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