引言
PHP图片抓取的基本原理
- cURL库:用于发送HTTP请求,获取网页内容。
- DOMDocument或SimpleXML:用于解析HTML和XML文档。
- 文件操作:用于保存抓取到的图片文件。
实战技巧一:使用cURL库发送请求
首先,确保您的PHP环境中已安装cURL扩展。以下是一个使用cURL库发送GET请求的示例代码:
<?php
$url = 'https://www.example.com/image.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
file_put_contents('image.jpg', $response);
} else {
echo '图片抓取失败:' . curl_error($ch);
}
?>
实战技巧二:解析HTML文档获取图片链接
<?php
$html = file_get_contents('https://www.example.com');
$dom = new DOMDocument();
@$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute('src');
echo "图片链接:$src\n";
}
?>
实战技巧三:下载图片并保存到本地
<?php
$url = 'https://www.example.com/image.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
file_put_contents('image.jpg', $response);
} else {
echo '图片下载失败:' . curl_error($ch);
}
?>
实战技巧四:批量抓取图片
<?php
$urls = [
'https://www.example.com/image1.jpg',
'https://www.example.com/image2.jpg',
// ...
];
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if ($response) {
$filename = basename($url);
file_put_contents($filename, $response);
} else {
echo "图片下载失败:$url\n";
}
}
?>