我建议分步思考。你必须做什么?
- 从远程 URL
complete 获取 HTML
- 抓取每张图片
complete
- 显示每张图片
todo
你有图片的 URL,现在怎么办?你想遍历每张图片。
旁注:您要抓取的每个图像都意味着一个新的 HTTP 请求(下载)。这会迅速增加加载时间。想一想:这就是我想要的吗?如果是这样,那么让我们分解一下:
第 1 步
从 URL 获取 HTML。
<?php
// Your URL
$url = 'https://twitter.com/dogethedog';
// Get HTML from your URL
$data = file_get_contents($url);
第 2 步
抓取每张图片。
// Grab every image source
preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $data, $out);
步骤 3a
对我们获得的每个图像 URL 执行此操作。
// Loop over every image source
foreach($out[1] as $imageURL){
步骤 3b
从我们的 URL 下载图像数据。
对于要显示的 Base64 编码图像,我们还需要图像的内容类型。这可以通过 PHP 函数curl_getinfo() 抓取。
More info about Base64 images in HTML
More info about cURL, it's safer with e.g. images
// Use cURL to fetch image data and image type
// We need image type to be able to properly display jpg, png, gif, ...
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // For https/ssl
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Standard cURL Option
// Fetch cURL Content
$imageData = curl_exec($ch);
$imageType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
// Close cURL Session
curl_close($ch);
步骤 3c
现在我们有了数据和图像类型,正确渲染<img> 标签。
// Image data gets to be fetched as BLOB, we need Base64
$imageDataEncoded = base64_encode($imageData);
// Build HTML <img> tag with proper type and base encoded image data
?>
<img src="data:<?php print $imageType ?>;base64,<?php print $imageDataEncoded ?>" alt="Could not fetch image">
<?php
}
?>