php: Get html source code with cURL

前端 未结 4 883
盖世英雄少女心
盖世英雄少女心 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: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();

提交回复
热议问题