0

I am getting content from my first website and displaying it on my other website by using file_get_contents() and I am using preg_replace() and preg_match() to modify the output the way I want it.

Now, there are images I would like to base64_encode() but I am stuck on figuring out how to do that?

If I use this line of code:

preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $fourth_content, $out)

I can print out all images src but it cannot encode them and send them back to the src.

Does anyone know how I can achieve this?

Draken
  • 3,134
  • 13
  • 34
  • 54
damircalusic
  • 17
  • 1
  • 5
  • 1
    i think you need to get the image file contents from `src` using `file_get_contents()` and then try to encode the image data. – Sasikumar Sep 13 '16 at 07:09

1 Answers1

1

I'd advise to think in steps. What is it you have to do?

  1. Fetch HTML from remote URL complete
  2. Grab every image complete
  3. 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

    }

?>
Community
  • 1
  • 1
Joachim
  • 304
  • 1
  • 9