Horje
How to convert all external image link from html string to base64 in PHP

See the example.


Full Code Example

Learn the Example.
index.php
Example: PHP
<?php
$html = '            <div class="itemer">
<span class="pointer" onclick="z49()">   
<center>
</br>    
<img src="https://website.sitelop.com/small/amazon.cn/icon.jpg" alt="Amazon.com. Spend less. Smile more." style="width:36px;height:36px; border-radius: 20%;" >
amazon.cn</center>     
</span> 
</div>

            <div class="itemer">
<span class="pointer" onclick="z50()">   
<center>
</br>    
<img src="https://website.sitelop.com/small/cnn.com/icon.jpg" alt="Breaking News, Latest News and Videos | CNN" style="width:36px;height:36px; border-radius: 20%;" >
cnn.com</center>     
</span> 
</div>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
        $src = $image->getAttribute('src');
        $type = pathinfo($src, PATHINFO_EXTENSION);
        $data = file_get_contents($src);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        $image->setAttribute("src", $base64); 
}
$html = $dom->saveHTML();

echo $html;
?>

Output should be:

Demo

Output should be:





html image

Related Articles
How to check Image error or valid in PHP PHP Image Tutorial
How to create Title to Image in PHP PHP Image Tutorial
How to convert a image link to Base64 in PHP PHP Image Tutorial
How to convert all external image link from html string to base64 in PHP PHP Image Tutorial


Read Full:
PHP Image Tutorial
Type:
Develop
Category:
Web Tutorial
Sub Category:
PHP Image Tutorial
Uploaded:
6 months ago
Uploaded by:
Admin
Views:
204
Tested on:
PHP 7


Reffered: https://stackoverflow.com/questions/48294816/find-and-convert-all-images-to-base64-from-html

Share on: