2017-04-25 40 views
0

獲取html頁面的內容下面是代碼:基本捲曲例如從遠程服務器

/* 
* Example to fetch the example.com homepage into a file 
*/ 

$curlObject = curl_init("http://AAA.BBB.CCC.DDD/");//AAA.BBB.CCC.DDD is the IP address of the remote server. 

$file = fopen("example_homepage.txt", "w"); 

curl_setopt($curlObject, CURLOPT_FILE, $file); 
curl_setopt($curlObject, CURLOPT_HEADER, 0); 

curl_exec($curlObject); 

curl_close($curlObject); 

fclose($file); 

它是基於例如here。我正在學習基本的cURL用法。預期的輸出是,在執行此PHP腳本後,應將位於安裝在我的遠程計算機(IP爲AAA.BBB.CCC.DDD)中的XAMPP服務器的htdocs目錄中的index.phpindex.html的內容複製到example_homepage.txt文件中。

現在創建了example_homepage.txt文件,但它是EMPTY。位於htdocs安裝在遠程機器中的XAMPP服務器的目錄中的主頁(index.phpindex.html)的內容不會複製到新創建的example_homepage.txt中。

問題是爲什麼以及如何解決這個問題?

回答

1
  1. 捲曲選項CURLOPT_FILE從來沒有真正爲我工作,也許越野車。不要使用它,還有其他方法。

  2. 爲了接收正文內容,請將選項CURLOPT_RETURNTRANSFER設置爲curl_setopt($curlObject, CURLOPT_RETURNTRANSFER, true);否則您將得不到任何內容。

  3. 這對我來說非常合適(file_put_contents()創建文件,如果它不存在)。

    <?php 
    $curlObject = curl_init("http://example.com/"); 
    curl_setopt($curlObject, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($curlObject); 
    curl_close($curlObject); 
    file_put_contents('example_homepage.txt', $result); 
    

我試了google.de,這是example_homepage.txt的內容:

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> 
<TITLE>301 Moved</TITLE></HEAD><BODY> 
<H1>301 Moved</H1> 
The document has moved 
<A HREF="http://www.google.de/">here</A>. 
</BODY></HTML> 

使用例如http://www.google.de/,它將按預期工作。