I'd advise to think in steps. What is it you have to do?
- Fetch HTML from remote URL
complete
- Grab every image
complete
- Display every image
todo
You have the image URLs, now what? You want to iterate over every image.
Sidenote: Every image you want to grab means a new HTTP request (download). This quickly builds up loading time. Think: is this what I want? If so, then let's break it down:
Step 1
Get HTML from URL.
<?php
// Your URL
$url = 'https://twitter.com/dogethedog';
// Get HTML from your URL
$data = file_get_contents($url);
Step 2
Grab every image.
// Grab every image source
preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $data, $out);
Step 3a
Do this for every image URL we got.
// Loop over every image source
foreach($out[1] as $imageURL){
Step 3b
Download the image data from our URL.
For a Base64 encoded image to display, we also need the content type of the image. This can be grabbed with PHP function 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);
Step 3c
Now that we have the data and image type, properly render the <img>
tag.
// 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
}
?>