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

后端 未结 5 1233
感动是毒
感动是毒 2021-01-21 06:57

What i\'m trying to achieve is this:

1st- I want to query a page like google but without filling it\'s search filed manually 2nd- I want to get the result and save it to

相关标签:
5条回答
  • 2021-01-21 07:20
    <?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;
    }
    ?>
    

    From the php manual...

    0 讨论(0)
  • 2021-01-21 07:22

    You should use cURL to do so, not only because it is way faster than file_get_contents, but also because it has many more features. Another reason to use it is that, as Xeoncross correctly mentioned in the comments, file_get_contents may be disabled by your webhost for security reasons.

    A basic example would be this one:

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

    If you need the return data from the request, you need to specify the CURLOPT_RETURNTRANSFER option:

    $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 );
    

    There are tons of cURL options, for example, you can set a request timeout:

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

    For a reference of all options see the curl_setopt() reference.

    0 讨论(0)
  • 2021-01-21 07:22
    $html = file_get_contents('http://example.com');
    

    is the simplest version you'll get.

    0 讨论(0)
  • 2021-01-21 07:31

    If you find the name of the field (q) you want to fill on the remote page (Google), you can fill it by using GET syntax:

    http://www.google.com/?q=hello
    
    0 讨论(0)
  • 2021-01-21 07:33

    You can use PHP CUrl, for detailed manupulations with the site you access!

    you can even perform get and posts on the site you access, or use services from different sites (in case the site provides services!).

    0 讨论(0)
提交回复
热议问题