Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[PHP] Remove Images with DOMDocument
// 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) {
// 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
You can’t perform that action at this time.