開發過程中,常需要一些通用的工具型函數。本文精選 20+ 高頻 PHP 代碼片段,涵蓋數據導出、解析、網絡請求、文件操作、圖片處理、地理計算、短網址、驗證碼、PDF 轉換等場景,代碼經過整理優化,可直接複製到項目中使用或封裝為工具類。
利用 fputcsv 寫入內存流,避免臨時文件,直接返回字符串供下載或存儲。
function generateCsv(array $data, string $delimiter = ',', string $enclosure = '"'): string {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
$contents = stream_get_contents($handle);
fclose($handle);
return $contents;
}
// 用法
$data = [
['apple', 'red', 10],
['orange', 'orange', 20]
];
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="export.csv"');
echo generateCsv($data);
使用 simplexml_load_string 快速將 XML 轉為對象遍歷。
$xmlStr = "<?xml version='1.0'?><moleculedb><molecule name='Benzine'><symbol>ben</symbol><code>A</code></molecule></moleculedb>";
$xml = simplexml_load_string($xmlStr);
foreach ($xml->molecule as $record) {
echo $record['name'] . ' ' . $record->symbol . ' ' . $record->code . "\n";
}
json_decode 默認返回對象,第二參數 true 返回關聯數組。
$json = '{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]}';
$obj = json_decode($json);
echo $obj->name; // rolf
echo $obj->office[0]; // google
用於登錄後跳轉回原頁、記錄來源頁等場景。
function current_url(): string {
$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return str_replace("&", "&", $url); // 修正實體
}
// 用法: header("Location: " . current_url());
原代碼使用已廢棄的 search.twitter.com,現需使用 Twitter API v2 + Bearer Token。此處保留邏輯結構供參考。
推薦使用 PHP 5.3+ 內置 DateTime::diff(),精確處理閏年、月份天數差異。
$date1 = new DateTime('2007-03-24');
$date2 = new DateTime('2009-06-26');
$interval = $date1->diff($date2);
echo "差值: {$interval->y} 年 {$interval->m} 月 {$interval->d} 日";
echo "總天數: {$interval->days} 天";
兼容舊版本或特殊需求時,可使用文中提供的 _date_diff 自定義函數(基於 Unix 時間戳)。
function deleteDir(string $path): bool {
if (is_dir($path)) {
$files = array_diff(scandir($path), ['.', '..']);
foreach ($files as $file) {
deleteDir(realpath($path) . '/' . $file);
}
return rmdir($path);
} elseif (is_file($path)) {
return unlink($path);
}
return false;
}
// 用法: deleteDir('images/');
使用 preg_replace 忽略大小寫替換,支持多關鍵字(空格分隔)。
function highlightKeywords(string $text, string $keywords): string {
$words = explode(' ', $keywords);
foreach ($words as $word) {
if ($word === '') continue;
$text = preg_replace("|($word)|Ui", '<span style="color:#4285F4;"><b>$1</b></span>', $text);
}
return $text;
}
$fp = fopen('blog.csv', 'a');
fputs($fp, "Hello World!\r\n");
fclose($fp);
使用 cURL 獲取二進制數據並寫入文件。
function downloadImage(string $url, string $saveAs): bool {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
]);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || empty($data)) return false;
return file_put_contents($saveAs, $data) !== false;
}
使用 filter_var 內置過濾器,簡潔可靠。
function isValidUrl(string $url): bool {
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
function generateQrCode(string $data, string $type = 'TXT', int $size = 150, string $ec = 'L', int $margin = 0): string {
$prefixes = ['URL' => 'https://', 'TEL' => 'TEL:', 'TXT' => '', 'EMAIL' => 'MAILTO:'];
if (!isset($prefixes[$type])) $type = 'TXT';
if (strpos($data, $prefixes[$type]) !== 0) $data = $prefixes[$type] . $data;
$data = urlencode($data);
$url = "https://chart.googleapis.com/chart?chs={$size}x{$size}&cht=qr&chld={$ec}|{$margin}&chl={$data}";
return file_get_contents($url); // 返回 PNG 二進制
}
// 用法: header('Content-Type: image/png'); echo generateQrCode('https://example.com', 'URL');
基於球面餘弦定理,返回英里、英尺、碼、公里、米。
function getDistance(float $lat1, float $lon1, float $lat2, float $lon2): array {
$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;
return [
'miles' => $miles,
'feet' => $miles * 5280,
'yards' => $miles * 5280 / 3,
'kilometers'=> $miles * 1.609344,
'meters' => $miles * 1609.344,
];
}
function ordinal(int $n): string {
$suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
$v = $n % 100;
return $n . ($v > 10 && $v < 20 ? 'th' : $suffix[$n % 10]);
}
echo ordinal(13); // 13th
適用於大文件下載帶寬控制,按塊發送並 sleep。
function downloadWithThrottle(string $localFile, string $downloadName, float $rateKBps = 20.5) {
if (!is_file($localFile)) die('File not found!');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($localFile));
header('Content-Disposition: filename=' . $downloadName);
$handle = fopen($localFile, 'rb');
while (!feof($handle)) {
echo fread($handle, round($rateKBps * 1024));
flush();
sleep(1);
}
fclose($handle);
}
header('Content-Type: image/png');
$text = $_GET['text'] ?? 'Demo';
$im = imagecreatefrompng('button.png'); // 底圖
$color = imagecolorallocate($im, 255, 255, 255);
$px = (imagesx($im) - 7.5 * strlen($text)) / 2;
imagestring($im, 1, $px, 9, $text, $color);
imagepng($im);
imagedestroy($im);
發送 HEAD 請求讀取 Content-Length 頭。
function remoteFilesize(string $url, string $user = '', string $pw = ''): string {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_NOBODY => true,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
if ($user && $pw) {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Basic ' . base64_encode("$user:$pw")]);
}
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
return $size >= 0 ? (string)$size : 'unknown';
}
需服務器安裝 ImageMagick 並授權 PHP exec 函數。
$pdf = './pdf/demo.pdf';
$jpg = './jpg/demo.jpg';
exec("convert \"$pdf\" -colorspace RGB -resize 800 \"$jpg\"", $out, $ret);
echo $ret === 0 ? 'Conversion OK' : 'Failed: ' . implode("\n", $out);
function getTinyUrl(string $url): string {
$ch = curl_init("https://tinyurl.com/api-create.php?url=" . urlencode($url));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 5]);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
解析頁面源碼提取 video_id、t 參數拼接下載 URL。當前 YouTube 已加密簽名,此方法多數失效,建議使用 youtube-dl 或官方 API。
function niceTime(string $date): string {
if (!$date) return 'No date';
$periods = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
$lengths = [60, 60, 24, 7, 4.35, 12, 10];
$now = time();
$unix = strtotime($date);
if (!$unix) return 'Bad date';
$diff = abs($now - $unix);
$tense = $now > $unix ? 'ago' : 'from now';
for ($j = 0; $diff >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$diff /= $lengths[$j];
}
$diff = round($diff);
if ($diff != 1) $periods[$j] .= 's';
return "$diff $periods[$j] $tense";
}
echo niceTime('2024-01-15 10:00'); // 輸出如 "2 days ago"
App\Utils\Helper 靜態類或 Trait,統一入口,便於維護與單元測試。exec、shell_exec 等高危函數,PDF 轉圖片請使用 PHP 擴展 imagick。