必须收藏的php实用代码片段
在编写代码的时候有个神奇的工具总是好的!下面这里收集了40+PHP代码片段,可以帮助你开发PHP项目。之前已经为大家分享了《必须收藏的23个php实用代码片段》。
这些PHP片段对于PHP初学者也非常有帮助,非常容易学习,让我们开始学习吧~
24.从PHP数据创建CSV文件
functiongenerateCsv($data,$delimiter=',',$enclosure='"'){
$handle=fopen('php://temp','r+');
foreach($dataas$line){
fputcsv($handle,$line,$delimiter,$enclosure);
}
rewind($handle);
while(!feof($handle)){
$contents.=fread($handle,8192);
}
fclose($handle);
return$contents;
}
语法:
<?php $data[0]="apple"; $data[1]="oranges"; generateCsv($data,$delimiter=',',$enclosure='"'); ?>
25.解析XML数据
$xml_string="<?xmlversion='1.0'?>
<moleculedb>
<moleculename='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<moleculename='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
//loadthexmlstringusingsimplexmlfunction
$xml=simplexml_load_string($xml_string);
//loopthroughtheeachnodeofmolecule
foreach($xml->moleculeas$record)
{
//attributeareaccesstedby
echo$record['name'],'';
//nodeareaccesstedby->operator
echo$record->symbol,'';
echo$record->code,'';
}
26.解析JSON数据
$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]}';
$obj=json_decode($json_string);
//printtheparseddata
echo$obj->name;//displaysrolf
echo$obj->office[0];//displaysgoogle
27.获取当前页面URL
这个PHP片段可以帮助你让用户登录后直接跳转到之前浏览的页面
functioncurrent_url()
{
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$validURL=str_replace("&","&",$url);
returnvalidURL;
}
语法:
<?php echo"Currentlyyouareon:".current_url(); ?>
28.从任意的Twitter账号获取最新的Tweet
functionmy_twitter($username)
{
$no_of_tweets=1;
$feed="http://search.twitter.com/search.atom?q=from:".$username."&rpp=".$no_of_tweets;
$xml=simplexml_load_file($feed);
foreach($xml->children()as$child){
foreach($childas$value){
if($value->getName()=="link")$link=$value['href'];
if($value->getName()=="content"){
$content=$value."";
echo'<pclass="twit">'.$content.'<aclass="twt"href="'.$link.'"title=""></a></p>';
}
}
}
}
语法:
<?php $handle="koonktech"; my_twitter($handle); ?>
29.转发数量
使用这个PHP片段可以检测你的页面URL有多少转发数量
functiontweetCount($url){
$content=file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
$element=newSimpleXmlElement($content);
$retweets=$element->story->url_count;
if($retweets){
return$retweets;
}else{
return0;
}
}
语法:
<?php $url="http://blog.koonk.com"; $count=tweetCount($url); return$count; ?>
30.计算两个日期的差
<?php
$date1=date('Y-m-d');
$date2="2015-12-04";
$diff=abs(strtotime($date2)-strtotime($date1));
$years=floor($diff/(365*60*60*24));
$months=floor(($diff-$years*365*60*60*24)/(30*60*60*24));
$days=floor(($diff-$years*365*60*60*24-$months*30*60*60*24)/(60*60*24));
printf("%dyears,%dmonths,%ddays\n",$years,$months,$days);
--------------------------------------------------------OR
$date1=newDateTime("2007-03-24");
$date2=newDateTime("2009-06-26");
$interval=$date1->diff($date2);
echo"difference".$interval->y."years,".$interval->m."months,".$interval->d."days";
//showsthetotalamountofdays(notdividedintoyears,monthsanddayslikeabove)
echo"difference".$interval->days."days";
--------------------------------------------------------OR
/**
*Calculatedifferencesbetweentwodateswithprecisesemantics.BasedonPHPsDateTime::diff()
*implementationbyDerickRethans.PortedtoPHPbyEmilH,2011-05-02.Norightsreserved.
*
*Seeherefororiginalcode:
*http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
*http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
*/
function_date_range_limit($start,$end,$adj,$a,$b,$result)
{
if($result[$a]<$start){
$result[$b]-=intval(($start-$result[$a]-1)/$adj)+1;
$result[$a]+=$adj*intval(($start-$result[$a]-1)/$adj+1);
}
if($result[$a]>=$end){
$result[$b]+=intval($result[$a]/$adj);
$result[$a]-=$adj*intval($result[$a]/$adj);
}
return$result;
}
function_date_range_limit_days($base,$result)
{
$days_in_month_leap=array(31,31,29,31,30,31,30,31,31,30,31,30,31);
$days_in_month=array(31,31,28,31,30,31,30,31,31,30,31,30,31);
_date_range_limit(1,13,12,"m","y",&$base);
$year=$base["y"];
$month=$base["m"];
if(!$result["invert"]){
while($result["d"]<0){
$month--;
if($month<1){
$month+=12;
$year--;
}
$leapyear=$year%400==0||($year%100!=0&&$year%4==0);
$days=$leapyear?$days_in_month_leap[$month]:$days_in_month[$month];
$result["d"]+=$days;
$result["m"]--;
}
}else{
while($result["d"]<0){
$leapyear=$year%400==0||($year%100!=0&&$year%4==0);
$days=$leapyear?$days_in_month_leap[$month]:$days_in_month[$month];
$result["d"]+=$days;
$result["m"]--;
$month++;
if($month>12){
$month-=12;
$year++;
}
}
}
return$result;
}
function_date_normalize($base,$result)
{
$result=_date_range_limit(0,60,60,"s","i",$result);
$result=_date_range_limit(0,60,60,"i","h",$result);
$result=_date_range_limit(0,24,24,"h","d",$result);
$result=_date_range_limit(0,12,12,"m","y",$result);
$result=_date_range_limit_days(&$base,&$result);
$result=_date_range_limit(0,12,12,"m","y",$result);
return$result;
}
/**
*Acceptstwounixtimestamps.
*/
function_date_diff($one,$two)
{
$invert=false;
if($one>$two){
list($one,$two)=array($two,$one);
$invert=true;
}
$key=array("y","m","d","h","i","s");
$a=array_combine($key,array_map("intval",explode("",date("YmdHis",$one))));
$b=array_combine($key,array_map("intval",explode("",date("YmdHis",$two))));
$result=array();
$result["y"]=$b["y"]-$a["y"];
$result["m"]=$b["m"]-$a["m"];
$result["d"]=$b["d"]-$a["d"];
$result["h"]=$b["h"]-$a["h"];
$result["i"]=$b["i"]-$a["i"];
$result["s"]=$b["s"]-$a["s"];
$result["invert"]=$invert?1:0;
$result["days"]=intval(abs(($one-$two)/86400));
if($invert){
_date_normalize(&$a,&$result);
}else{
_date_normalize(&$b,&$result);
}
return$result;
}
$date="2014-12-0419:37:22";
echo'<pre>';
print_r(_date_diff(strtotime($date),time()));
echo'</pre>';
?>
31.删除文件夹内容
functionDelete($path)
{
if(is_dir($path)===true)
{
$files=array_diff(scandir($path),array('.','..'));
foreach($filesas$file)
{
Delete(realpath($path).'/'.$file);
}
returnrmdir($path);
}
elseif(is_file($path)===true)
{
returnunlink($path);
}
returnfalse;
}
语法:
<?php $path="images/"; Delete($path);//Thiswilldeleteimagesfolderalongwithitscontents. ?>
32.搜索和高亮字符串中的关键字
functionhighlighter_text($text,$words)
{
$split_words=explode("",$words);
foreach($split_wordsas$word)
{
$color="#4285F4";
$text=preg_replace("|($word)|Ui",
"<spanstyle=\"color:".$color.";\"><b>$1</b></span>",$text);
}
return$text;
}
语法:
<?php $string="IlikechocolatesandIlikeapples"; $words="apple"; echohighlighter_text($string,$words); ?>
33.写入文件
<? $filename='blog.csv'; $fp=fopen($filename,'w'); $output="Hello"; $output.="World!"; $output.="\r\n"; fputs($fp,$output); fclose($fp); ?>
34.根据URL下载图片
functionimagefromURL($image,$rename)
{
$ch=curl_init($image);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close($ch);
$fp=fopen("$rename",'w');
fwrite($fp,$rawdata);
fclose($fp);
}
语法:
<?php $url="http://koonk.com/images/logo.png"; $rename="koonk.png"; imagefromURL($url,$rename); ?>
35.检测URL是否有效
functionisvalidURL($url)
{
$check=0;
if(filter_var($url,FILTER_VALIDATE_URL)!==false){
$check=1;
}
return$check;
}
语法:
<?php $url="http://koonk.com"; $check=checkvalidURL($url); echo$check;//ifreturns1thenURLisvalid. ?>
36.生成二维码
functionqr_code($data,$type="TXT",$size='150',$ec='L',$margin='0')
{
$types=array("URL"=-->"http://","TEL"=>"TEL:","TXT"=>"","EMAIL"=>"MAILTO:");
if(!in_array($type,array("URL","TEL","TXT","EMAIL")))
{
$type="TXT";
}
if(!preg_match('/^'.$types[$type].'/',$data))
{
$data=str_replace("\\","",$types[$type]).$data;
}
$ch=curl_init();
$data=urlencode($data);
curl_setopt($ch,CURLOPT_URL,'http://chart.apis.google.com/chart');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,false);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
$response=curl_exec($ch);
curl_close($ch);
return$response;
}
语法:
<?php
header("Content-type:image/png");
echoqr_code("http://koonk.com","URL");
?>
37.计算两个地图坐标之间的距离
functiongetDistanceBetweenPointsNew($latitude1,$longitude1,$latitude2,$longitude2){
$theta=$longitude1-$longitude2;
$miles=(sin(deg2rad($latitude1))*sin(deg2rad($latitude2)))+(cos(deg2rad($latitude1))*cos(deg2rad($latitude2))*cos(deg2rad($theta)));
$miles=acos($miles);
$miles=rad2deg($miles);
$miles=$miles*60*1.1515;
$feet=$miles*5280;
$yards=$feet/3;
$kilometers=$miles*1.609344;
$meters=$kilometers*1000;
returncompact('miles','feet','yards','kilometers','meters');
}
语法:
<?php
$point1=array('lat'=>40.770623,'long'=>-73.964367);
$point2=array('lat'=>40.758224,'long'=>-73.917404);
$distance=getDistanceBetweenPointsNew($point1['lat'],$point1['long'],$point2['lat'],$point2['long']);
foreach($distanceas$unit=>$value){
echo$unit.':'.number_format($value,4).'';
}
?>
38.获取一个特定话题标签的所有Tweets
functiongetTweets($hash_tag){
$url='http://search.twitter.com/search.atom?q='.urlencode($hash_tag);
echo"<p>Connectingto<strong>$url</strong>...</p>";
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$xml=curl_exec($ch);
curl_close($ch);
//IfyouwanttoseetheresponsefromTwitter,uncommentthisnextpartout:
//echo"<p>Response:</p>";
//echo"<pre>".htmlspecialchars($xml)."</pre>";
$affected=0;
$twelement=newSimpleXMLElement($xml);
foreach($twelement->entryas$entry){
$text=trim($entry->title);
$author=trim($entry->author->name);
$time=strtotime($entry->published);
$id=$entry->id;
echo"<p>Tweetfrom".$author.":<strong>".$text."</strong><em>Posted".date('n/j/yg:ia',$time)."</em></p>";
}
returntrue;
}
39.添加th,st,nd或者rd作为数字的后缀
Fridaythe13th
functionordinal($cdnl){
$test_c=abs($cdnl)%10;
$ext=((abs($cdnl)%100<21&&abs($cdnl)%100>4)?'th'
:(($test_c<4)?($test_c<3)?($test_c<2)?($test_c<1)
?'th':'st':'nd':'rd':'th'));
return$cdnl.$ext;
}
语法:
<?php $number=10; echoordinal($number);//outputis10th ?>
40.限制文件下载的速度
<?php
//localfilethatshouldbesendtotheclient
$local_file='test-file.zip';
//filenamethattheusergetsasdefault
$download_file='your-download-name.zip';
//setthedownloadratelimit(=>20,5kb/s)
$download_rate=20.5;
if(file_exists($local_file)&&is_file($local_file)){
//sendheaders
header('Cache-control:private');
header('Content-Type:application/octet-stream');
header('Content-Length:'.filesize($local_file));
header('Content-Disposition:filename='.$download_file);
//flushcontent
flush();
//openfilestream
$file=fopen($local_file,"r");
while(!feof($file)){
//sendthecurrentfileparttothebrowser
printfread($file,round($download_rate*1024));
//flushthecontenttothebrowser
flush();
//sleeponesecond
sleep(1);
}
//closefilestream
fclose($file);}
else{
die('Error:Thefile'.$local_file.'doesnotexist!');
}
?>
41.把文本转换成图片
<?php
header("Content-type:image/png");
$string=$_GET['text'];
$im=imagecreatefrompng("images/button.png");
$color=imagecolorallocate($im,255,255,255);
$px=(imagesx($im)-7.5*strlen($string))/2;
$py=9;
$fontSize=1;
imagestring($im,fontSize,$px,$py,$string,$color);
imagepng($im);
imagedestroy($im);
?>
42.获取远程文件的大小
functionremote_filesize($url,$user="",$pw="")
{
ob_start();
$ch=curl_init($url);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch,CURLOPT_NOBODY,1);
if(!empty($user)&&!empty($pw))
{
$headers=array('Authorization:Basic'.base64_encode("$user:$pw"));
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
}
$ok=curl_exec($ch);
curl_close($ch);
$head=ob_get_contents();
ob_end_clean();
$regex='/Content-Length:\s([0-9].+?)\s/';
$count=preg_match($regex,$head,$matches);
returnisset($matches[1])?$matches[1]:"unknown";
}
语法
<?php $file="http://koonk.com/images/logo.png"; $size=remote_filesize($url); echo$size; ?>
43.使用imagebrick进行pdf到图像的转换
<?php
$pdf_file='./pdf/demo.pdf';
$save_to='./jpg/demo.jpg';//makesurethatapachehaspermissionstowriteinthisfolder!(commonproblem)
//executeImageMagickcommand'convert'andconvertPDFtoJPGwithappliedsettings
exec('convert"'.$pdf_file.'"-colorspaceRGB-resize800"'.$save_to.'"',$output,$return_var);
if($return_var==0){//ifexecsuccessfulyconvertedpdftojpg
print"ConversionOK";
}
elseprint"Conversionfailed.".$output;
?>
44.使用tinyurl生成短网址
functionget_tiny_url($url)
{
$ch=curl_init();
$timeout=5;
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data=curl_exec($ch);
curl_close($ch);
return$data;
}
语法:
<?php $url="http://blog.koonk.com/2015/07/Hello-World"; $tinyurl=get_tiny_url($url); echo$tinyurl; ?>
45.youtube下载链接生成器
使用下面的PHP片段可以让你的用户下载Youtube视频
functionstr_between($string,$start,$end)
{
$string="".$string;$ini=strpos($string,$start);if($ini==0)return"";$ini+=strlen($start);$len=strpos($string,$end,$ini)-$ini;returnsubstr($string,$ini,$len);}
functionget_youtube_download_link(){
$youtube_link=$_GET['youtube'];
$youtube_page=file_get_contents($youtube_link);
$v_id=str_between($youtube_page,"&video_id=","&");
$t_id=str_between($youtube_page,"&t=","&");
$flv_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id";
$hq_flv_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=6";
$mp4_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=18";
$threegp_link="http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&fmt=17";
echo"\t\tDownload(right-click>saveas):\n\t\t";
echo"<ahref=\"$flv_link\">FLV</a>\n\t\t";
echo"<ahref=\"$hq_flv_link\">HQFLV(ifavailable)</a>\n\t\t";
echo"<ahref=\"$mp4_link\">MP4</a>\n\t\t";
echo"<ahref=\"$threegp_link\">3GP</a>\n";
}
46.Facebook样式的时间戳
Facebook(xminsage,yhoursagoetc)
functionnicetime($date)
{
if(empty($date)){
return"Nodateprovided";
}
$periods=array("second","minute","hour","day","week","month","year","decade");
$lengths=array("60","60","24","7","4.35","12","10");
$now=time();
$unix_date=strtotime($date);
//checkvalidityofdate
if(empty($unix_date)){
return"Baddate";
}
//isitfuturedateorpastdate
if($now>$unix_date){
$difference=$now-$unix_date;
$tense="ago";
}else{
$difference=$unix_date-$now;
$tense="fromnow";
}
for($j=0;$difference>=$lengths[$j]&&$j<count($lengths)-1;$j++){
$difference/=$lengths[$j];
}
$difference=round($difference);
if($difference!=1){
$periods[$j].="s";
}
return"$difference$periods[$j]{$tense}";
}
语法:
<?php $date="2015-07-0503:45"; $result=nicetime($date);//2daysago ?>
以上就是本文的全部内容,希望对大家的学习有所帮助。