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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line