7个实用的PHP代码片段分享
1、简易的页面缓存方案
若项目未采用CMS或主流框架,构建轻量级缓存机制能显著优化小网站的访问体验。以下代码逻辑简单,但能有效解决静态资源加载问题。
具体实现代码如下:
<?php
// 定义缓存文件的路径及名称
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// 设置文件保留时长(秒),此处设定为5小时
$cachetime = 18000;
// 检查缓存文件是否新鲜。若是,则直接输出并终止脚本。
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内容。
<?php
// 完成!将缓存内容保存至文件
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// 最后向浏览器发送输出
ob_end_flush();
?> 点击查看详细教程:http://wesbos.com/simple-php-page-caching-technique/
2、PHP中计算地理距离
这是一个基于经纬度计算两点间距离的高效函数。它支持返回英里、公里和海里三种单位的结果。
代码实现如下:
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;
}
}使用示例:
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers";
点击查看详细案例:http://www.phpsnippets.info/calculate-distances-in-php
3、将秒数转换为时间格式
该函数可将总秒数智能转换为年、月、日、小时等更易读的时间单位组合。
代码实现如下:
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}点击查看完整源码:http://ckorp.net/sec2time.php
4、强制触发文件下载
对于MP3等媒体文件,浏览器通常会直接播放。若需强制用户下载,可使用以下代码设置响应头。
function downloadFile($file){
$file_name = $file;
$mime = 'application/force-download';
header('Pragma: public'); // 必需
header('Expires: 0'); // 禁止缓存
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); // 推送数据
exit();
}
来源:Credit: Alessio Delmonti
5、通过Google API获取天气
只需3行代码即可查询当前天气。将代码中的ADDRESS替换为目标城市即可。
$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();
点击查看详细教程:http://ortanotes.tumblr.com/post/200469319/current-weather-in-3-lines-of-php
6、根据地址获取经纬度
随着Google Maps API的普及,获取特定地点的经纬度变得常见。此函数接收地址参数,返回包含经纬度的数组。
function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}点击查看源码:http://snipplr.com/view.php?codeview&id=47806
7、使用PHP和Google获取Favicon
Web应用常需引用其他网站的Favicon图标。借助Google服务和PHP可轻松实现,前提是网络连接正常。
function get_favicon($url){
$url = str_replace("http://",'',$url);
return "http://www.google.com/s2/favicons?domain=".$url;
}点击查看源码:http://snipplr.com/view.php?codeview&id=45928