Php 从远程服务器获取html页面内容的基本示例

Php 从远程服务器获取html页面内容的基本示例,php,curl,Php,Curl,代码如下: /* * 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, C

代码如下:

/*
* 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);
它是以这个例子为基础的。我正在学习卷发的基本用法。预期的输出是,在执行此php脚本后,应将安装在远程计算机(其IP为
AAA.BBB.CCC.DDD
)中XAMPP服务器的
htdocs
目录中的
index.php
index.html
的内容复制到示例_homepage.txt文件中

现在创建了
example\u homepage.txt
文件,但该文件是空的。
位于远程机器中安装的XAMPP服务器的
htdocs
目录中的主页(
index.php
index.html
)的内容不会复制到新创建的
example\u homepage.txt

问题是为什么以及如何解决这个问题?

  • curl选项CURLOPT_文件对我来说从来没有真正起过作用,可能是bug。别用它,还有其他的方法

  • 要接收正文内容,请使用
    curl\u setopt($curlObject,CURLOPT\u RETURNTRANSFER,true)设置选项CURLOPT\u RETURNTRANSFER
  • 这对我来说非常有效(如果文件不存在,则file\u put\u 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);
    
    <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>