php: Get html source code with cURL

前端 未结 4 866
盖世英雄少女心
盖世英雄少女心 2020-11-27 18:26

How can I get the html source code of http://www.example-webpage.com/file.html without using file_get_contents()?

I need to know this becau

相关标签:
4条回答
  • 2020-11-27 18:56
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);
    

    Source: http://www.christianschenk.org/blog/php-curl-allow-url-fopen/

    0 讨论(0)
  • 2020-11-27 18:57

    Try the following:

    $ch = curl_init("http://www.example-webpage.com/file.html");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $content = curl_exec($ch);
    curl_close($ch);
    

    I would only recommend this for small files. Big files are read as a whole and are likely to produce a memory error.

    edit: after some discussion in the comments we found out that the problem was that the servercouldnt resolve the host name and the page was in addition a https resource so here comes your temporary solution (until your serveradmin fixes the name resolving).

    what i did is just pinging graph.facebook.com to see the ip adress, replace the hostname by the ip adress and instead give the header manually. this however renders the ssl certificate invalid so we have to supress peer verification

    //$url = "https://graph.facebook.com/19165649929?fields=name";
    $url = "https://66.220.146.224/19165649929?fields=name";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: graph.facebook.com'));
    $output = curl_exec($ch);
    curl_close($ch); 
    

    keep in mind that the ip adress might change and this is an eror source. you should as well do some error handling using curl_error();

    0 讨论(0)
  • 2020-11-27 19:17

    I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

    0 讨论(0)
  • 2020-11-27 19:19

    Try http://php.net/manual/en/curl.examples-basic.php :)

    <?php
    
    $ch = curl_init("http://www.example.com/");
    $fp = fopen("example_homepage.txt", "w");
    
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    $output = curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    ?>
    

    As the documentation says:

    The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

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