Must be a collection of PHP useful code snippets,
It's always good to have a magical tool when writing code! Here is a collection of 40+ PHP code snippets to help you develop your PHP project. We have previously shared the 23 PHP useful snippets that must be collected.
These PHP snippets are also very helpful for beginners in PHP, so it's easy to learn, so let's start learning ~
24. Create a CSV file from PHP data
function Generatecsv ($data, $delimiter = ', ', $enclosure = ' "') { $handle = fopen (' php://temp ', ' r+ '); foreach ($data as $line) { fputcsv ($handle, $line, $delimiter, $enclosure); } Rewind ($handle); while (!feof ($handle)) { $contents. = Fread ($handle, 8192); } Fclose ($handle); return $contents;}
Grammar:
<?php$data[0] = "Apple"; $data [1] = "oranges"; Generatecsv ($data, $delimiter = ', ', $enclosure = ' "');? >
25. Parsing XML Data
$xml _string= "<?xml version= ' 1.0 '?>
ben
A
H2O
";
K
Load the XML string using simplexml Function$xml = simplexml_load_string ($xml _string); Loop through the each node of Moleculeforeach ($xml->molecule as $record) { //attribute is accessted by Ech o $record [' name '], '; Node is accessted by-and operator Echo $record->symbol, "; echo $record->code, ';}
26. Parsing JSON Data
$json _string= ' {"id": 1, "name": "Rolf", "Country": "Russia", "office": ["Google", "Oracle"]} '; $obj =json_decode ($json _ string);//print the parsed Dataecho $obj->name; Displays Rolfecho $obj->office[0]; Displays Google
27. Get the current page URL
This PHP snippet can help you get the user to log in and jump directly to the previously viewed page
function Current_url () {$url = "http://". $_server[' Http_host '). $_server[' Request_uri ']; $validURL = Str_replace (" & "," & ", $url); return validurl;}
Grammar:
<?phpecho "Currently you is on:". Current_url ();? >
28. Get the latest tweets from any Twitter account
function My_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 ($child as $value) { if ($value->getname () = = "link") $link = $ value[' href ']; if ($value->getname () = = "Content") { $content = $value. ""; Echo ''. $content. '
'; } } } }
Grammar:
<?php$handle = "Koonktech"; My_twitter ($handle);? >
29. Number of forwards
Use this PHP fragment to detect how many forwards you have in your page URL
function Tweetcount ($url) { $content = file_get_contents ("http://api.tweetmeme.com/url_info?url=". $url); $element = new SimpleXMLElement ($content); $retweets = $element->story->url_count; if ($retweets) { return $retweets; } else { return 0;} }
Grammar:
<?php$url = "http://blog.koonk.com"; $count = Tweetcount ($url); return $count; >
30. Calculate the difference of two dates
<?php$date1 = Date (' y-m-d '), $date 2 = "2015-12-04", $diff = ABS (Strtotime ($date 2)-Strtotime ($date 1)); $years = Floor ($ Diff/(365*60*60*24)); $months = Floor (($diff-$years * 365*60*60*24)/(30*60*60*24)), $days = Floor (($diff-$years * 36 5*60*60*24-$months *30*60*60*24)/(60*60*24));p rintf ("%d years,%d months,%d days\n", $years, $months, $days);--------- -----------------------------------------------or$date1 = new DateTime ("2007-03-24"), $date 2 = new DateTime (" 2009-06-26 "), $interval = $date 1->diff ($date 2); echo" Difference ". $interval->y. "Years,". $interval->m. "Months,". $interval->d. "Days";//shows the total amount of days (not divided into years, months and Days like above) echo "difference". $interval->days. "Days";--------------------------------------------------------or/** * Calculate differences between the date s with precise semantics. Based on PHPs DateTime::d iff () * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved. * * See here for original code: * 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) {$re sult[$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, +, "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%! = 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%! = 0 && $year% 4 = = 0); $days = $leapyear? $days _in_month_leap[$month]: $days _in_month[$month]; $result ["D"] + = $days; $result ["M"]--; $month + +; if ($month >) {$month-= 12; $year + +; }}} return $result;} function _date_normalize ($base, $result) {$result = _date_range_limit (0, a, "s", "I", $result); $result = _date_range_limit (0, Max, "I", "H", $result); $result = _date_range_limit (0, a, "H", "D", $result); $result = _date_range_limit (0, N, a, "M", "Y", $result); $result = _date_range_limit_dayS (& $base, & $result); $result = _date_range_limit (0, N, a, "M", "Y", $result); return $result;} /** * accepts, UNIX timestamps. */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 ("Y m D H i S", $one)))); $b = Array_combine ($key, Array_map ("Intval", Explode ("", Date ("Y m D H i S", $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-04 19:37:22"; Echo '';p Rint_r (_date_diff (Strtotime ($date), Time ()), Echo '
';? >
31. Delete Folder Contents
function Delete ($path) { if (is_dir ($path) = = = True) { $files = Array_diff (Scandir ($path), Array ('. ', '. ')); foreach ($files as $file) { Delete (Realpath ($path). '/' . $file); } return rmdir ($path); } else if (is_file ($path) = = = True) { return unlink ($path); } return false;}
Grammar:
<?php$path = "images/";D elete ($path); This would delete images folder along with its contents.? >
32. Search and Highlight keywords in a string
function Highlighter_text ($text, $words) { $split _words = Explode ("", $words); foreach ($split _words as $word) { $color = "#4285F4"; $text = Preg_replace ("| ( $word) | Ui ", "$ ", $text); } return $text;}
Grammar:
<?php$string = "I like chocolates and I like apples"; $words = "Apple"; Echo Highlighter_text ($string, $words); >
33. Writing Files
< $filename = ' blog.csv '; $fp = fopen ($filename, ' W '); $output = "Hello"; $output. = "world!"; $output. = "\ r \ n"; fputs ($fp, $output); fclose ($FP);? >
34. Download the picture according to the URL
function Imagefromurl ($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);}
Grammar:
<?php$url = "Http://koonk.com/images/logo.png"; $rename = "Koonk.png"; Imagefromurl ($url, $rename);? >
35. Detect if the URL is valid
Grammar:
<?php$url = "http://koonk.com"; $check = Checkvalidurl ($url); Echo $check; If returns 1 then URLs is valid.? >
36. Generate two-dimensional code
function Qr_code ($data, $type = "TXT", $size = ' =--> ', $ec = ' L ', $margin = ' 0 ') { $types = array ("URL" "/http", " Tel "=" and "Tel:", "TXT" and "", "EMAIL" and "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,); $response = curl_exec ($ch); Curl_close ($ch); return $response;}
Grammar:
<?phpheader ("Content-type:image/png"); Echo qr_code ("http://koonk.com", "URL"); >
37. Calculate the distance between the two map coordinates
function Getdistancebetweenpointsnew ($latitude 1, $longitude 1, $latitude 2, $longitude 2) { $theta = $longitude 1-$ Longitude2; $miles = (sin (Deg2rad ($latitude 1)) * Sin (Deg2rad ($latitude 2)) + (cos (Deg2rad ($latitude 1)) * cos (Deg2rad ($latitude 2)) * Cos (Deg2rad ($theta))); $miles = ACOs ($miles); $miles = Rad2deg ($miles); $miles = $miles * 1.1515; $feet = $miles * 5280; $yards = $feet/3; $kilometers = $miles * 1.609344; $meters = $kilometers *; Return compact (' Miles ', ' feet ', ' yards ', ' kilometers ', ' meters ');
Grammar:
<?php$point1 = Array (' lat ' = = 40.770623, ' long ' = -73.964367); $point 2 = Array (' lat ' = = 40.758224, ' Long ' => ; -73.917404); $distance = getdistancebetweenpointsnew ($point 1[' lat '), $point 1[' long '], $point 2[' lat ', $point 2[' long ' ]), foreach ($distance as $unit = + $value) { echo $unit. ': '. Number_format ($value, 4). "; >
38. Get all Tweets for a specific topic tag
function Gettweets ($hash _tag) { $url = ' http://search.twitter.com/search.atom?q= '. UrlEncode ($hash _tag); echo "$url ...
"; $ch = Curl_init ($url); curl_setopt ($ch, Curlopt_returntransfer, TRUE); $xml = curl_exec ($ch); Curl_close ($ch); If you want to see the response from Twitter, uncomment this next part out: //echo "Response:
"; echo "". Htmlspecialchars ($xml)."
"; $affected = 0; $twelement = new SimpleXMLElement ($xml); foreach ($twelement->entry as $entry) { $text = Trim ($entry->title); $author = Trim ($entry->author->name); $time = Strtotime ($entry->published); $id = $entry->id; echo "". $text." Posted ". Date (' n/j/y g:i a ', $time)."
"; } return true;}
39. Add Th,st,nd or Rd as the number suffix
Friday the 13thfunction ordinal ($cdnl) { $test _c = ABS ($CDNL)%; $ext = (ABS ($CDNL)%100 < && 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;}
Grammar:
<?php$number = 10;echo ordinal ($number); Output is 10th?>
40. Limit the speed of file downloads
<?php//local file that should is send to the Client$local_file = ' test-file.zip ';//filename that th E user gets as Default$download_file = ' your-download-name.zip '; Set the download rate limit (= = 20,5 kb/s) $download _rate = 20.5;if (file_exists ($local _file) && is_file ($loca L_file)) {//Send Headers header (' cache-control:private '); Header (' Content-type:application/octet-stream '); Header (' Content-length: '. FileSize ($local _file)); Header (' content-disposition:filename= '. $download _file); Flush content flush (); Open file Stream $file = fopen ($local _file, "R"); while (!feof ($file)) {//Send the current file part to the browser print fread ($file, round ($download _rate * 1024) ); Flush the content to the browser flush (); Sleep One Second sleep (1); }//Close file stream fclose ($file);} else {die (' error:the file '. $local _file, ' does not exist! ');}?
41. Convert Text to Images
<?phpheader ("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;imag Estring ($im, FontSize, $px, $py, $string, $color); Imagepng ($im); Imagedestroy ($im);? >
42. Get the remote file size
function Remote_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); return Isset ($matches [1])? $matches [1]: "Unknown";}
Grammar
<?php$file = "Http://koonk.com/images/logo.png"; $size = Remote_filesize ($url); Echo $size; >
43. Convert PDF to image using Imagebrick
<?php$pdf_file = './pdf/demo.pdf '; $save _to = './jpg/demo.jpg '; Make sure that Apache have permissions to write on this folder! (common problem)//execute ImageMagick command ' convert ' and convert PDF to JPG with applied settingsexec (' Convert '. $pdf _ File. ' "-colorspace rgb-resize" '. $save _to. ' "', $output, $return _var); if ($return _var = = 0) { //if exec successful Y converted pdf To jpg print "Conversion OK";} else print "Conversion failed." $output;? >
44. Generate Short URLs using TinyURL
function Get_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; }
Grammar:
<?php$url = "Http://blog.koonk.com/2015/07/Hello-World"; $tinyurl = Get_tiny_url ($url); Echo $tinyurl; >
YouTube Download Chain Builder
Use the PHP snippet below to get your users to download Youtube videos
function Str_between ($string, $start, $end) {$string = "". $string; $ini = Strpos ($string, $start); if ($ini = = 0) return ""; $ini + = strlen ($start); $len = Strpos ($string, $end, $ini)-$ini; Return substr ($string, $ini, $len); }function Get_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"; $MP 4_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 > Save As): \n\t\t"; echo "flv\n\t\t"; echo "HQ FLV (if available) \n\t\t"; echo "mp4\n\t\t"; echo "3gp\n";}
The time stamp of Facebook style
Facebook (x mins age, Y hours ago etc) function Nicetime ($date) { if (empty ($date)) { return ' No date provided '; } $periods = Array ("Second", "Minute", "Hour", "Day", "Week", "Month", "year", "decade"); $lengths = Array ("Ten", "" "," "" , "7", "4.35", "N", "Max"); $now = time (); $unix _date = Strtotime ($date); Check validity of date if (empty ($unix _date)) { return "bad Date"; } Is it the future date or past date if ($now > $unix _date) { $difference = $now-$unix _date; $tense = "Ago"; } else { $difference = $unix _date-$now; $tense = "from"; } 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}";}
Grammar:
<?php$date = "2015-07-05 03:45"; $result = Nicetime ($date); 2 Days ago?>
The above is the whole content of this article, I hope that everyone's study has helped.
Articles you may be interested in:
- 7 super-useful PHP code Snippets
- 10 useful snippets of PHP code
- Common string processing code snippet collation in PHP
- Super-Functional 7 PHP snippet sharing
- PHP Security Detection Code snippet (share)
- 19 Super-useful PHP code Snippets
- 9 Classic PHP Code snippets to share
- 9 Useful PHP code snippets to share
- 10 super-useful PHP code Snippets
- 6 super-useful PHP code Snippets
http://www.bkjia.com/PHPjc/1098695.html www.bkjia.com true http://www.bkjia.com/PHPjc/1098695.html techarticle must be a collection of PHP practical code snippets, in writing code, there is a magic tool is always good! Here is a collection of 40+ PHP code snippets to help you develop your PHP project. The ...