-
-
Save tommcfarlin/35581dce7a46c4a78f5168d0291aa961 to your computer and use it in GitHub Desktop.
[PHP] Remove Images with DOMDocument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Instantiate a DOMDocument object and load the incoming $description HTML. | |
$domDocument = new DOMDocument(); | |
$domContent = $domDocument->loadHTML(mb_convert_encoding($description, 'HTML-ENTITIES')); | |
// Find all of the images in the HTML. | |
$images = $domDocument->getElementsByTagName('img'); | |
// If there are images, then iterate through each of them. | |
if (0 !== \count($images)) { | |
$urlPrefix = $this->getUrlPrefix(); // A helper function for getting the URL prefix. | |
foreach ($images as $image) { | |
$image->setAttribute( | |
'src', | |
$urlPrefix.$image->getAttribute('src') | |
); | |
// If the image's source results in a 404 status code, set the `src` to an empty string. | |
if (!$this->isValidImage($image->getAttribute('src'))) { | |
$image->setAttribute('src', ''); | |
} | |
} | |
} | |
// Save the changed document and send it to the front-end. | |
return $domDocument->saveHTML(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment