必须收藏的php实用代码片段

在编写代码的时候有个神奇的工具总是好的!下面这里收集了 40+ PHP 代码片段,可以帮助你开发PHP 项目。 之前已经为大家分享了《必须收藏的23个php实用代码片段》。

这些PHP 片段对于PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧~

24. 从 PHP 数据创建 CSV 文件

  1. function generateCsv($data, $delimiter = ',', $enclosure = '"') {
  2. $handle = fopen('php://temp', 'r+');
  3. foreach ($data as $line) {
  4. fputcsv($handle, $line, $delimiter, $enclosure);
  5. }
  6. rewind($handle);
  7. while (!feof($handle)) {
  8. $contents .= fread($handle, 8192);
  9. }
  10. fclose($handle);
  11. return $contents;
  12. }

语法:

  1. <?php
  2. $data[0] = "apple";
  3. $data[1] = "oranges";
  4. generateCsv($data, $delimiter = ',', $enclosure = '"');
  5. ?>

25. 解析 XML 数据

  1. $xml_string="<?xml version='1.0'?>
  2. <moleculedb>
  3. <molecule name='Benzine'>
  4. <symbol>ben</symbol>
  5. <code>A</code>
  6. </molecule>
  7. <molecule name='Water'>
  8. <symbol>h2o</symbol>
  9. <code>K</code>
  10. </molecule>
  11. </moleculedb>";
  12. //load the xml string using simplexml function
  13. $xml = simplexml_load_string($xml_string);
  14. //loop through the each node of molecule
  15. foreach ($xml->molecule as $record)
  16. {
  17. //attribute are accessted by
  18. echo $record['name'], ' ';
  19. //node are accessted by -> operator
  20. echo $record->symbol, ' ';
  21. echo $record->code, '';
  22. }

26. 解析 JSON 数据

  1. $json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
  2. $obj=json_decode($json_string);
  3. //print the parsed data
  4. echo $obj->name; //displays rolf
  5. echo $obj->office[0]; //displays google

27. 获取当前页面 URL

这个 PHP 片段可以帮助你让用户登录后直接跳转到之前浏览的页面

  1. function current_url()
  2. {
  3. $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  4. $validURL = str_replace("&", "&", $url);
  5. return validURL;
  6. }

语法:

  1. <?php
  2. echo "Currently you are on: ".current_url();
  3. ?>

28. 从任意的 Twitter 账号获取最新的 Tweet

  1. function my_twitter($username)
  2. {
  3. $no_of_tweets = 1;
  4. $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $no_of_tweets;
  5. $xml = simplexml_load_file($feed);
  6. foreach($xml->children() as $child) {
  7. foreach ($child as $value) {
  8. if($value->getName() == "link") $link = $value['href'];
  9. if($value->getName() == "content") {
  10. $content = $value . "";
  11. echo '<p class="twit">'.$content.' <a class="twt" href="'.$link.'" title=""> </a></p>';
  12. }
  13. }
  14. }
  15. }

语法:

  1. <?php
  2. $handle = "koonktech";
  3. my_twitter($handle);
  4. ?>

29. 转发数量

使用这个 PHP 片段可以检测你的页面 URL 有多少转发数量

  1. function tweetCount($url) {
  2. $content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
  3. $element = new SimpleXmlElement($content);
  4. $retweets = $element->story->url_count;
  5. if($retweets){
  6. return $retweets;
  7. } else {
  8. return 0;
  9. }
  10. }

语法:

  1. <?php
  2. $url = "http://blog.koonk.com";
  3. $count = tweetCount($url);
  4. return $count;
  5. ?>

30. 计算两个日期的差

  1. <?php
  2. $date1 = date( 'Y-m-d' );
  3. $date2 = "2015-12-04";
  4. $diff = abs(strtotime($date2) - strtotime($date1));
  5. $years = floor($diff / (365*60*60*24));
  6. $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
  7. $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
  8. printf("%d years, %d months, %d days\n", $years, $months, $days);
  9. -------------------------------------------------------- OR
  10. $date1 = new DateTime("2007-03-24");
  11. $date2 = new DateTime("2009-06-26");
  12. $interval = $date1->diff($date2);
  13. echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
  14. // shows the total amount of days (not divided into years, months and days like above)
  15. echo "difference " . $interval->days . " days ";
  16. -------------------------------------------------------- OR
  17. /**
  18. * Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff()
  19. * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved.
  20. *
  21. * See here for original code:
  22. * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
  23. * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
  24. */
  25. function _date_range_limit($start, $end, $adj, $a, $b, $result)
  26. {
  27. if ($result[$a] < $start) {
  28. $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1;
  29. $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1);
  30. }
  31. if ($result[$a] >= $end) {
  32. $result[$b] += intval($result[$a] / $adj);
  33. $result[$a] -= $adj * intval($result[$a] / $adj);
  34. }
  35. return $result;
  36. }
  37. function _date_range_limit_days($base, $result)
  38. {
  39. $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  40. $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  41. _date_range_limit(1, 13, 12, "m", "y", &$base);
  42. $year = $base["y"];
  43. $month = $base["m"];
  44. if (!$result["invert"]) {
  45. while ($result["d"] < 0) {
  46. $month--;
  47. if ($month < 1) {
  48. $month += 12;
  49. $year--;
  50. }
  51. $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
  52. $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
  53. $result["d"] += $days;
  54. $result["m"]--;
  55. }
  56. } else {
  57. while ($result["d"] < 0) {
  58. $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
  59. $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
  60. $result["d"] += $days;
  61. $result["m"]--;
  62. $month++;
  63. if ($month > 12) {
  64. $month -= 12;
  65. $year++;
  66. }
  67. }
  68. }
  69. return $result;
  70. }
  71. function _date_normalize($base, $result)
  72. {
  73. $result = _date_range_limit(0, 60, 60, "s", "i", $result);
  74. $result = _date_range_limit(0, 60, 60, "i", "h", $result);
  75. $result = _date_range_limit(0, 24, 24, "h", "d", $result);
  76. $result = _date_range_limit(0, 12, 12, "m", "y", $result);
  77. $result = _date_range_limit_days(&$base, &$result);
  78. $result = _date_range_limit(0, 12, 12, "m", "y", $result);
  79. return $result;
  80. }
  81. /**
  82. * Accepts two unix timestamps.
  83. */
  84. function _date_diff($one, $two)
  85. {
  86. $invert = false;
  87. if ($one > $two) {
  88. list($one, $two) = array($two, $one);
  89. $invert = true;
  90. }
  91. $key = array("y", "m", "d", "h", "i", "s");
  92. $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one))));
  93. $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two))));
  94. $result = array();
  95. $result["y"] = $b["y"] - $a["y"];
  96. $result["m"] = $b["m"] - $a["m"];
  97. $result["d"] = $b["d"] - $a["d"];
  98. $result["h"] = $b["h"] - $a["h"];
  99. $result["i"] = $b["i"] - $a["i"];
  100. $result["s"] = $b["s"] - $a["s"];
  101. $result["invert"] = $invert ? 1 : 0;
  102. $result["days"] = intval(abs(($one - $two)/86400));
  103. if ($invert) {
  104. _date_normalize(&$a, &$result);
  105. } else {
  106. _date_normalize(&$b, &$result);
  107. }
  108. return $result;
  109. }
  110. $date = "2014-12-04 19:37:22";
  111. echo '<pre>';
  112. print_r( _date_diff( strtotime($date), time() ) );
  113. echo '</pre>';
  114. ?>

31. 删除文件夹内容

  1. function Delete($path)
  2. {
  3. if (is_dir($path) === true)
  4. {
  5. $files = array_diff(scandir($path), array('.', '..'));
  6. foreach ($files as $file)
  7. {
  8. Delete(realpath($path) . '/' . $file);
  9. }
  10. return rmdir($path);
  11. }
  12. else if (is_file($path) === true)
  13. {
  14. return unlink($path);
  15. }
  16. return false;
  17. }

语法:

  1. <?php
  2. $path = "images/";
  3. Delete($path); // This will delete images folder along with its contents.
  4. ?>

32. 搜索和高亮字符串中的关键字

  1. function highlighter_text($text, $words)
  2. {
  3. $split_words = explode( " " , $words );
  4. foreach($split_words as $word)
  5. {
  6. $color = "#4285F4";
  7. $text = preg_replace("|($word)|Ui" ,
  8. "<span color:".$color.";\"><b>$1</b></span>" , $text );
  9. }
  10. return $text;
  11. }

语法:

  1. <?php
  2. $string = "I like chocolates and I like apples";
  3. $words = "apple";
  4. echo highlighter_text($string ,$words);
  5. ?>

33. 写入文件

  1. <?
  2. $filename = 'blog.csv';
  3. $fp = fopen($filename, 'w');
  4. $output = " Hello ";
  5. $output .= " World! ";
  6. $output .= "\r\n";
  7. fputs($fp, $output);
  8. fclose($fp);
  9. ?>

34. 根据 URL 下载图片

  1. function imagefromURL($image,$rename)
  2. {
  3. $ch = curl_init($image);
  4. curl_setopt($ch, CURLOPT_HEADER, 0);
  5. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  6. curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  7. $rawdata=curl_exec ($ch);
  8. curl_close ($ch);
  9. $fp = fopen("$rename",'w');
  10. fwrite($fp, $rawdata);
  11. fclose($fp);
  12. }

语法:

  1. <?php
  2. $url = "http://koonk.com/images/logo.png";
  3. $rename = "koonk.png";
  4. imagefromURL($url,$rename);
  5. ?>

35. 检测 URL 是否有效

  1. function isvalidURL($url)
  2. {
  3. $check = 0;
  4. if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
  5. $check = 1;
  6. }
  7. return $check;
  8. }

语法:

  1. <?php
  2. $url = "http://www.phpfensi.com";
  3. $check = checkvalidURL($url);
  4. echo $check; //if returns 1 then URL is valid.
  5. ?>

36. 生成二维码

  1. function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0')
  2. {
  3. $types = array("URL" =--> "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:");
  4. if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL")))
  5. {
  6. $type = "TXT";
  7. }
  8. if (!preg_match('/^'.$types[$type].'/', $data))
  9. {
  10. $data = str_replace("\\", "", $types[$type]).$data;
  11. }
  12. $ch = curl_init();
  13. $data = urlencode($data);
  14. curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart');
  15. curl_setopt($ch, CURLOPT_POST, true);
  16. curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  18. curl_setopt($ch, CURLOPT_HEADER, false);
  19. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  20. $response = curl_exec($ch);
  21. curl_close($ch);
  22. return $response;
  23. }

语法:

  1. <?php
  2. header("Content-type: image/png");
  3. echo qr_code("http://koonk.com", "URL");
  4. ?>

37. 计算两个地图坐标之间的距离

  1. function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
  2. $theta = $longitude1 - $longitude2;
  3. $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
  4. $miles = acos($miles);
  5. $miles = rad2deg($miles);
  6. $miles = $miles * 60 * 1.1515;
  7. $feet = $miles * 5280;
  8. $yards = $feet / 3;
  9. $kilometers = $miles * 1.609344;
  10. $meters = $kilometers * 1000;
  11. return compact('miles','feet','yards','kilometers','meters');
  12. }

语法:

  1. <?php
  2. $point1 = array('lat' => 40.770623, 'long' => -73.964367);
  3. $point2 = array('lat' => 40.758224, 'long' => -73.917404);
  4. $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
  5. foreach ($distance as $unit => $value) {
  6. echo $unit.': '.number_format($value,4).'';
  7. }
  8. ?>

38. 获取一个特定话题标签的所有 Tweets

  1. function getTweets($hash_tag) {
  2. $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
  3. echo "<p>Connecting to <strong>$url</strong> ...</p>";
  4. $ch = curl_init($url);
  5. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
  6. $xml = curl_exec ($ch);
  7. curl_close ($ch);
  8. //If you want to see the response from Twitter, uncomment this next part out:
  9. //echo "<p>Response:</p>";
  10. //echo "<pre>".htmlspecialchars($xml)."</pre>";
  11. $affected = 0;
  12. $twelement = new SimpleXMLElement($xml);
  13. foreach ($twelement->entry as $entry) {
  14. $text = trim($entry->title);
  15. $author = trim($entry->author->name);
  16. $time = strtotime($entry->published);
  17. $id = $entry->id;
  18. echo "<p>Tweet from ".$author.": <strong>".$text."</strong> <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
  19. }
  20. return true ;
  21. }

39. 添加 th,st,nd 或者 rd 作为数字的后缀

  1. Friday the 13th
  2. function ordinal($cdnl){
  3. $test_c = abs($cdnl) % 10;
  4. $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th'
  5. : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
  6. ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
  7. return $cdnl.$ext;
  8. }

语法:

  1. <?php
  2. $number = 10;
  3. echo ordinal($number); //output is 10th
  4. ?>

40. 限制文件下载的速度

  1. <?php
  2. // local file that should be send to the client
  3. $local_file = 'test-file.zip';
  4. // filename that the user gets as default
  5. $download_file = 'your-download-name.zip';
  6. // set the download rate limit (=> 20,5 kb/s)
  7. $download_rate = 20.5;
  8. if(file_exists($local_file) && is_file($local_file)) {
  9. // send headers
  10. header('Cache-control: private');
  11. header('Content-Type: application/octet-stream');
  12. header('Content-Length: '.filesize($local_file));
  13. header('Content-Disposition: filename='.$download_file);
  14. // flush content
  15. flush();
  16. // open file stream
  17. $file = fopen($local_file, "r");
  18. while(!feof($file)) {
  19. // send the current file part to the browser
  20. print fread($file, round($download_rate * 1024));
  21. // flush the content to the browser
  22. flush();
  23. // sleep one second
  24. sleep(1);
  25. }
  26. // close file stream
  27. fclose($file);}
  28. else {
  29. die('Error: The file '.$local_file.' does not exist!');
  30. }
  31. ?>

41. 把文本转换成图片

  1. <?php
  2. header("Content-type: image/png");
  3. $string = $_GET['text'];
  4. $im = imagecreatefrompng("images/button.png");
  5. $color = imagecolorallocate($im, 255, 255, 255);
  6. $px = (imagesx($im) - 7.5 * strlen($string)) / 2;
  7. $py = 9;
  8. $fontSize = 1;
  9. imagestring($im, fontSize, $px, $py, $string, $color);
  10. imagepng($im);
  11. imagedestroy($im);
  12. ?>

42. 获取远程文件的大小

  1. function remote_filesize($url, $user = "", $pw = "")
  2. {
  3. ob_start();
  4. $ch = curl_init($url);
  5. curl_setopt($ch, CURLOPT_HEADER, 1);
  6. curl_setopt($ch, CURLOPT_NOBODY, 1);
  7. if(!emptyempty($user) && !emptyempty($pw))
  8. {
  9. $headers = array('Authorization: Basic ' . base64_encode("$user:$pw"));
  10. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  11. }
  12. $ok = curl_exec($ch);
  13. curl_close($ch);
  14. $head = ob_get_contents();
  15. ob_end_clean();
  16. $regex = '/Content-Length:\s([0-9].+?)\s/';
  17. $count = preg_match($regex, $head, $matches);
  18. return isset($matches[1]) ? $matches[1] : "unknown";
  19. }

语法

  1. <?php
  2. $file = "http://www.phpfensi.com/images/logo.png";
  3. $size = remote_filesize($url);
  4. echo $size;
  5. ?>

43. 使用 imagebrick 进行 pdf 到图像的转换

  1. <?php
  2. $pdf_file = './pdf/demo.pdf';
  3. $save_to = './jpg/demo.jpg'; //make sure that apache has permissions to write in this folder! (common problem)
  4. //execute ImageMagick command 'convert' and convert PDF to JPG with applied settings
  5. exec('convert "'.$pdf_file.'" -colorspace RGB -resize 800 "'.$save_to.'"', $output, $return_var);
  6. if($return_var == 0) { //if exec successfuly converted pdf to jpg
  7. print "Conversion OK";
  8. }
  9. else print "Conversion failed.".$output;
  10. ?>

44. 使用 tinyurl 生成短网址

  1. function get_tiny_url($url)
  2. {
  3. $ch = curl_init();
  4. $timeout = 5;
  5. curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
  6. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  7. curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  8. $data = curl_exec($ch);
  9. curl_close($ch);
  10. return $data;
  11. }

语法:

  1. <?php
  2. $url = "http://blog.koonk.com/2015/07/Hello-World";
  3. $tinyurl = get_tiny_url($url);
  4. echo $tinyurl;
  5. ?>

45. youtube 下载链接生成器

使用下面的 PHP 片段可以让你的用户下载 Youtube 视频

  1. function str_between($string, $start, $end)
  2. {
  3. $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); }
  4. function get_youtube_download_link(){
  5. $youtube_link = $_GET['youtube'];
  6. $youtube_page = file_get_contents($youtube_link);
  7. $v_id = str_between($youtube_page, "&video_&");
  8. $t_id = str_between($youtube_page, "&t=", "&");
  9. $flv_link = "http://www.youtube.com/get_video?video_;
  10. $hq_flv_link = "http://www.youtube.com/get_video?video_;
  11. $mp4_link = "http://www.youtube.com/get_video?video_;
  12. $threegp_link = "http://www.youtube.com/get_video?video_;
  13. echo "\t\tDownload (right-click > save as):\n\t\t";
  14. echo "<a href=\"$flv_link\">FLV</a>\n\t\t";
  15. echo "<a href=\"$hq_flv_link\">HQ FLV (if available)</a>\n\t\t";
  16. echo "<a href=\"$mp4_link\">MP4</a>\n\t\t";
  17. echo "<a href=\"$threegp_link\">3GP</a>\n";
  18. }

46. Facebook 样式的时间戳

  1. Facebook (x mins age, y hours ago etc)
  2. function nicetime($date)
  3. {
  4. if(emptyempty($date)) {
  5. return "No date provided";
  6. }
  7. $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
  8. $lengths = array("60","60","24","7","4.35","12","10");
  9. $now = time();
  10. $unix_date = strtotime($date);
  11. // check validity of date
  12. if(emptyempty($unix_date)) {
  13. return "Bad date";
  14. }
  15. // is it future date or past date
  16. if($now > $unix_date) {
  17. $difference = $now - $unix_date;
  18. $tense = "ago";
  19. } else {
  20. $difference = $unix_date - $now;
  21. $tense = "from now";
  22. }
  23. for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
  24. $difference /= $lengths[$j];
  25. }
  26. $difference = round($difference);
  27. if($difference != 1) {
  28. $periods[$j].= "s";
  29. }
  30. return "$difference $periods[$j] {$tense}";
  31. }

语法:

  1. <?php
  2. $date = "2015-07-05 03:45";
  3. $result = nicetime($date); // 2 days ago
  4. ?>