# Case 1:How to automagically make responsive images from all the images in the page
To make responsive images we're going to use the DomDocument to wrap the images in a div that has the class of 'responsive-img'.
function makeResposiveImages($html='')
{
// Create a DOMDocument
$dom = new DOMDocument();
// Load html including utf8, like Hebrew
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
// Create the div wrapper
$div = $dom->createElement('div');
$div->setAttribute('class', 'responsive-img');
// Get all the images
$images = $dom->getElementsByTagName('img');
// Loop the images
foreach ($images as $image)
{
//Clone our created div
$new_div_clone = $div->cloneNode();
//Replace image with wrapper div
$image->parentNode->replaceChild($new_div_clone,$image);
//Append image to wrapper div
$new_div_clone->appendChild($image);
}
// Save the HTML
$html = $dom->saveHTML();
return $html;
}
To use the DomDocument class we first need to instantiate it using
$dom = new DOMDocument();
When loading the HTML it is desirable to use the UTF-8 parameter for languages other than English.
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
We create a wrapping div for the images that has the class 'responsive-img'
$div = $dom->createElement('div');
$div->setAttribute('class', 'responsive-img');
In order to extract the images from the HTML:
$images = $dom->getElementsByTagName('img');
Next, we loop through the images and wrap each one with the wrapping div.
At the end, we save the changes with:
$html = $dom->saveHTML();