I am trying to add automatically width and height to all images from the page but for some reason it's adding about 3 times the width and height to the image and it's working very hard. From my tests getimagesize
function is the issue of loading hard, but for repeating the width and height on every img tag 3 time I don't get it.
REGEX VERSION
$html = file_get_contents('http://www.inspiredhealing.org');
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
$html = preg_replace( '/(width)="\d*"\s/', "", $html );
$html = str_replace('width="60"', '', $html);
$img_sources = preg_match_all('/< *img[^>]*src *= *["\']?([^"\']*)/i', $html, $images);
foreach($images[1] as $src) {
$image_size = getimagesize($src);
$html = str_replace($src.'"', $src.'" '.$image_size[3], $html);
}
var_dump($html);
DOM DOCUMENT VERSION
$html = file_get_contents('http://www.inspiredhealing.org');
$dom = new domDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
$html = preg_replace( '/(width)="\d*"\s/', "", $html );
$html = str_replace('width="60"', '', $html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
$img_sources = array();
foreach ($images as $image) {
if($image->getAttribute('src') !== '') {
array_push($img_sources, $image->getAttribute('src'));
}
}
foreach($img_sources as $src) {
$image_size = getimagesize($src);
var_dump($image_size);
//$html = str_replace($src.'"', $src.'" '.$image_size[3], $html);
}
var_dump($html);
I added the version with dom document, but still script runs slow and it gets to the image the width and height attribute 5 times, it's true that in the array I get 5 times same link, but how to add correctly. Array $img_sources
would be smth like this:
array(
'fb.png',
'fb.png',
'fb.png'
....
)
so it ads to the same tags but on all instanced of fb.png 5 times the width and height instead of adding it 1 time to each element of the array. So the issue stands in the foreach($img_sources as $src) {
but how to overcome this.