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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化