php教程

PHP采集网页所有图片地址方法

php教程 51源码 2024-04-01 人阅读

1、 file_get_contents获取页面

通过PHP的内置函数`file_get_contents`来获取页面的内容。

例如,以下代码将获取一个名为`example.html`的本地HTML文件的内容:

$html = file_get_contents('example.html');

2、正则表达式找出图片链接

以下是一个简单的代码示例,采集的目标站不同,可能表达式需要些许改动。

// 定义正则表达式模式
$pattern = '/<img.*?src="(.*?)"/';
// 在HTML页面中查找图片链接
preg_match_all($pattern, $html, $matches);
// 输出图片链接列表
foreach ($matches[1] as $match) {
    echo $match . '<br>';
}

完整示例

// 获取HTML页面的内容
$html = file_get_contents('http://example.com/page.html');
// 定义正则表达式模式
$pattern = '/<img.*?src="(.*?)"/';
// 在HTML页面中查找图片链接
preg_match_all($pattern, $html, $matches);
// 输出图片链接数量
echo '共找到' . count($matches[1]) . '个图片链接<br>';
// 输出图片链接列表
foreach ($matches[1] as $match) {
    echo $match . '<br>';
}


版权声明:文章搜集于网络,如有侵权请联系本站,转载请说明出处:https://www.51yma.cn/jiaocheng/php/1450.html
文章来源:
标签 采集教程