以下是一个简单的PHP实例,用于爬取网页上的图片并下载到本地服务器。这个例子使用了cURL库来发送HTTP请求,并解析HTML以找到图片URL。
实例步骤
1. 环境准备
确保你的PHP环境中安装了cURL扩展。

2. 创建PHP脚本
创建一个名为`download_images.php`的PHP文件。
3. 编写脚本
```php
// 目标网页URL
$url = 'http://example.com';
// 创建cURL会话
$ch = curl_init($url);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行cURL会话
$html = curl_exec($ch);
// 关闭cURL会话
curl_close($ch);
// 图片下载函数
function downloadImage($imageUrl, $savePath) {
// 创建cURL会话
$ch = curl_init($imageUrl);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行cURL会话
$imageData = curl_exec($ch);
// 关闭cURL会话
curl_close($ch);
// 保存图片到本地
file_put_contents($savePath, $imageData);
}
// 解析HTML并下载图片
$dom = new DOMDocument();
@$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute('src');
$savePath = 'downloaded_images/' . basename($src);
downloadImage($src, $savePath);
}
echo "







