dsqpx86002 2014-09-12 08:10
浏览 41
已采纳

从url检索数据并保存在php中

I am trying to retrieve the html from file get contents in php then save it to a php file so I can include it into my homepage.

Unfortunately my script isn't saving the data into the file. I also need to verwrite this data on a daily basis as it will be setup with a cron job.

Can anyone tell me where I am going wrong please? I am just learning php :-)

<?php 
$richSnippets = file_get_contents('http://website.com/data');
$filename = 'reviews.txt';
$handle = fopen($filename,"x+");
$somecontent = echo $richSnippets;
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?> 
  • 写回答

2条回答 默认 最新

  • dougong2005 2014-09-12 08:18
    关注

    A couple of things,

    http://website.com/data gets a 404 error, it doesn't exist.

    Change your code to

    $site = 'http://www.google.com';
    $homepage = file_get_contents($site);
    $filename = 'reviews.txt';
    $handle = fopen($filename,"w");
    fwrite($handle,$homepage);
    echo "Success";
    fclose($handle);
    

    Remove $somecontent = echo $richSnippets; it doesn't do anything.

    if you have the proper permissions it should work.

    Be sure that your pointing to an existing webpage.

    Edit

    When cURL is enabled you can use the following function

    function get_web_page( $url ){
      $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
      );
    
      $ch      = curl_init( $url );
      curl_setopt_array( $ch, $options );
      $content = curl_exec( $ch );
      curl_close( $ch );
    
      return $content;
    }
    

    Now change

    $homepage = file_get_contents($site);
    

    in to

    $homepage = get_web_page($site);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?