首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

40+ 個 PHP 實用代碼片段大全(含 CSV、XML、JSON、圖片、二維碼、地理距離等)

     編輯:PHP 相關知識

40+ 個 PHP 實用代碼片段大全(含 CSV、XML、JSON、圖片、二維碼、地理距離等)

開發過程中,常需要一些通用的工具型函數。本文精選 20+ 高頻 PHP 代碼片段,涵蓋數據導出、解析、網絡請求、文件操作、圖片處理、地理計算、短網址、驗證碼、PDF 轉換等場景,代碼經過整理優化,可直接複製到項目中使用或封裝為工具類。

24. 從數組生成 CSV 文件內容

利用 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);

25. 解析 XML 字符串

使用 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";
}

26. 解析 JSON 數據

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

27. 獲取當前完整 URL

用於登錄後跳轉回原頁、記錄來源頁等場景。

function current_url(): string {
    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    return str_replace("&", "&", $url); // 修正實體
}
// 用法: header("Location: " . current_url());

28. 獲取指定 Twitter 用戶最新推文(需 API v1.1 以上版本調整)

原代碼使用已廢棄的 search.twitter.com,現需使用 Twitter API v2 + Bearer Token。此處保留邏輯結構供參考。

29. 獲取頁面轉發數(原 Tweetmeme API 已停用,建議改用 Twitter API 或自建統計)

30. 計算兩個日期的差值(年/月/日)

推薦使用 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 時間戳)。

31. 遞歸刪除目錄及其所有內容

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/');

32. 搜索並高亮關鍵字

使用 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;
}

33. 寫入文件(追加模式)

$fp = fopen('blog.csv', 'a');
fputs($fp, "Hello World!\r\n");
fclose($fp);

34. 根據 URL 下載圖片到本地

使用 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;
}

35. 驗證 URL 格式是否合法

使用 filter_var 內置過濾器,簡潔可靠。

function isValidUrl(string $url): bool {
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

36. 生成二維碼(調用 Google Chart API,現建議使用本地庫如 BaconQrCode)

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');

37. 計算兩個經緯度坐標間的距離

基於球面餘弦定理,返回英里、英尺、碼、公里、米。

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,
    ];
}

38. 獲取話題標簽相關推文(同 28,需遷移至 Twitter API v2)

39. 為數字添加序數後綴(1st, 2nd, 3rd, 4th...)

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

40. 限制文件下載速度

適用於大文件下載帶寬控制,按塊發送並 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);
}

41. 將文本繪製到圖片上(簡易驗證碼/圖片生成)

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);

42. 獲取遠程文件大小(不下載內容)

發送 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';
}

43. 使用 ImageMagick 將 PDF 轉為圖片

需服務器安裝 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);

44. 使用 TinyURL 生成短網址

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;
}

45. 獲取 YouTube 視頻下載鏈接(僅供學習,注意版權與服務條款)

解析頁面源碼提取 video_id、t 參數拼接下載 URL。當前 YouTube 已加密簽名,此方法多數失效,建議使用 youtube-dl 或官方 API。

46. Facebook 風格的相對時間顯示(如 "2 hours ago")

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,統一入口,便於維護與單元測試。
  • 涉及外部 API(Twitter、Google Chart、TinyURL)的片段,需關注官方變更,建議遷移至官方 SDK 或成熟第三方庫。
  • 文件操作、網絡請求務必加入異常處理、超時控制、重試機制。
  • 生產環境禁用 exec、shell_exec 等高危函數,PDF 轉圖片請使用 PHP 擴展 imagick。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved