this might be a funky question, but I wonder if anyone could think of a way how to take a chunk of html, scan it for <img>
tags and if the tag has no width+height value apply it with list($width, $height, $type, $attr);
?
More in detail, I have a php page that includes another page with html only. I would want the html to be changed before output to browser.
This is a simplified version of what I am looking at:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<?php
include_once("client-contributed-text-and-images.php");
?>
</div>
</body>
</html>
after some input below I came up with following:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<?php
$dom = new DOMDocument();
$dom->loadHTMLFile("client-contributed-text-and-images.php");
foreach ($dom->getElementsByTagName('img') as $item) {
$item->setAttribute('width', '100');
echo $dom->saveHTML();
exit;
}
?>
</div>
</body>
</html>
The problem is that it generates a complete html4 file in the middle, while only changing the first img tag and seemingly not outputting the code afterwards:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><img src="img1.jpg" width="100"><h1>header</h1>
<p>some text</p>
<a href="http://google.com">some link</a>
<img src="img2.jpg"></body></html>
so I switched gears and tried fopen() instead and got it to work partly:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<?php
$root = realpath($_SERVER['DOCUMENT_ROOT']);
$file = $root."/client-contributed-text-and-images.php";
$f = fopen($file, 'r');
$contents = fread($f, filesize($file));
fclose($f);
$new_contents = str_replace("<img ", "<img width='100' height='100' ", $contents);
echo $new_contents;
?>
</div>
</body>
</html>
which gave:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<img width='100' height='100' src="img1.jpg">
<h1>header</h1>
<p>some text</p>
<a href="http://google.com">some link</a>
<img width='100' height='100' src="img2.jpg"></div>
</body>
</html>
Now I just need some help with figuring out how to implement list($width, $height, $type, $attr);
to include right with and height (and obviously only when it is not already set).