为什么要用PHP自动化日常任务?或者如何让电脑替你工作
\n\n想象一下:每天早上你登录服务器,运行数据库备份,检查错误日志,生成昨天的报告并发送给老板。然后——再来一次,再来一次。无聊吗?当然。更关键的是,把程序员的时间浪费在机器能做的事情上是很愚蠢的。
\n\nPHP不仅仅用于网站。这门语言非常适合PHP任务自动化:从简单的文件重命名到复杂的网站抓取。在本文中,我将展示10个真实示例,它们能为你节省数小时的工作时间。所有脚本都是可用的、经过验证的——拿来就用。
\n\n顺便说一句,如果你正在寻找使用PHP进行自动化的现成解决方案——你来对地方了。开始吧!
\n\n1. 自动发送带附件的电子邮件(PDF报告)
\n\n来自业务方最常见的请求:“让报告自动发送”。下面是一个发送带PDF文件邮件的简单脚本。
\n\n<?php\nfunction sendReportWithAttachment($to, $subject, $body, $filePath) {\n $boundary = md5(time());\n \n $headers = "MIME-Version: 1.0\\r\\n";\n $headers .= "From: report@mysite.com\\r\\n";\n $headers .= "Content-Type: multipart/mixed; boundary=\\"{$boundary}\\"\\r\\n";\n \n $message = "--{$boundary}\\r\\n";\n $message .= "Content-Type: text/plain; charset=utf-8\\r\\n\\r\\n";\n $message .= $body . "\\r\\n\\r\\n";\n \n if (file_exists($filePath)) {\n $content = file_get_contents($filePath);\n $content = chunk_split(base64_encode($content));\n $message .= "--{$boundary}\\r\\n";\n $message .= "Content-Type: application/pdf; name=\\"" . basename($filePath) . "\\"\\r\\n";\n $message .= "Content-Disposition: attachment; filename=\\"" . basename($filePath) . "\\"\\r\\n";\n $message .= "Content-Transfer-Encoding: base64\\r\\n\\r\\n";\n $message .= $content . "\\r\\n";\n }\n \n $message .= "--{$boundary}--";\n \n return mail($to, $subject, $message, $headers);\n}\n\n// 使用方式:\nsendReportWithAttachment(\n 'boss@company.com',\n '每日报告 ' . date('d.m.Y'),\n '附件中是PDF报告。详情见文件。',\n '/var/reports/daily_report.pdf'\n);\n?>\n\n如何自动化: 将此脚本放入cron中每天执行一次——报告就会自动发送。
\n\n2. 抓取网站并保存数据到CSV
\n\n假设你需要收集竞争对手的价格或职位列表。PHP抓取很简单。使用cURL和DOMDocument。
\n\n<?php\nfunction parseSiteToCSV($url, $cssSelector, $outputFile) {\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);\n curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');\n \n $html = curl_exec($ch);\n curl_close($ch);\n \n if (!$html) {\n return false;\n }\n \n $dom = new DOMDocument();\n @$dom->loadHTML($html);\n $xpath = new DOMXPath($dom);\n \n $items = $xpath->query($cssSelector);\n \n $file = fopen($outputFile, 'w');\n fputcsv($file, ['文本', '链接']);\n \n foreach ($items as $item) {\n $text = trim($item->textContent);\n $link = $item->getAttribute('href') ?: '—';\n fputcsv($file, [$text, $link]);\n }\n \n fclose($file);\n return true;\n}\n\n// 示例:从网站抓取新闻标题\nparseSiteToCSV(\n 'https://news.ycombinator.com/',\n '//tr[@class="athing"]/td[@class="title"]/a',\n 'hacker_news_titles.csv'\n);\n?>\n\n这个PHP任务自动化示例可以每小时运行一次——无需点击即可获取最新数据。
\n\n