php tips小集

在老外BLOG看到10个PHP的小TIPS,看上去不是很主流,但有的时候估计还很有用的,故笔记之
1 简单页面cache
   <?php
    // define the path and name of cached file
    $cachefile = 'cached-files/'.date('M-d-Y').'.php';
    // define how long we want to keep the file in seconds. I set mine to 5 hours.
    $cachetime = 18000;
    // Check if the cached file is still fresh. If it is, serve it up and exit.
    if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    include($cachefile);
        exit;
    }
    // if there is either no file OR the file to too old, render the page and capture the HTML.
    ob_start();
?>
    <html>
        output all your html here.
    </html>
<?php
    // We're done! Save the cached content to a file
    $fp = fopen($cachefile, 'w');
    fwrite($fp, ob_get_contents());
    fclose($fp);
    // finally send browser output
    ob_end_flush();
?>


2 知道两点的经度伟度计算距离
   function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

3 比如有时象MP3等文件,要浏览器强制下载而不是用MP打开,可以这样 
  function downloadFile($file){
        $file_name = $file;
        $mime = 'application/force-download';
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile($file_name); // push it out
exit();
}

4 使用GOOGLE API获得某个地址的天气预报
   $xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS');
  $information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition");
  echo $information[0]->attributes();

5 获得某个网站的收藏夹图标
   function get_favicon($url){
  $url = str_replace("http://",'',$url);
  return "http://www.google.com/s2/favicons?domain=".$url;
}

你可能感兴趣的:(PHP,xml,cache,Google,FP)