如何使用PHP向网页发出请求


How to make a request to a web page with PHP?

我想要实现的是:

第一-我想查询像谷歌一样的页面,但不需要手动填写它的搜索文件第二-我想得到结果并将其保存到数据库

我在这里看到了一个用C#做这件事的例子

http://www.farooqazam.net/c-sharp-auto-click-button-and-auto-fill-form/comment-page-1/#comment-27256

但我想用php来做,你能帮我吗?

感谢

您应该使用cURL来实现这一点,不仅因为它比file_get_contents快得多,还因为它有更多的功能。使用它的另一个原因是,正如Xeoncross在评论中正确提到的那样,出于安全原因,file_get_contents可能会被您的网络主机禁用。

一个基本的例子是:

$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );

如果您需要请求的返回数据,则需要指定CURLOPT_RETURNTRANSFER选项:

$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://example.com' );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true ); // Fetch the contents too
$html = curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );

有很多cURL选项,例如,您可以设置请求超时:

curl_setopt( $curl_handle, CURLOPT_CONNECTTIMEOUT, 2 ); // 2 second timeout

有关所有选项的引用,请参阅curl_setopt((引用。

$html = file_get_contents('http://example.com');

是最简单的版本。

<?php
$r = new HttpRequest('http://example.com/feed.rss', HttpRequest::METH_GET);
$r->setOptions(array('lastmodified' => filemtime('local.rss')));
$r->addQueryData(array('category' => 3));
try {
    $r->send();
    if ($r->getResponseCode() == 200) {
        file_put_contents('local.rss', $r->getResponseBody());
    }
} catch (HttpException $ex) {
    echo $ex;
}
?>

从php手册。。。

您可以使用PHP CUrl,对您访问的网站进行详细的操作!

你甚至可以在你访问的网站上执行获取和发布,或者使用不同网站的服务(以防该网站提供服务!(。

如果您在远程页面(Google(上找到要填写的字段(q(的名称,您可以使用GET语法进行填写:

http://www.google.com/?q=hello