这可能是一个时髦的问题,但我想知道是否有人能想到一种方法如何获取一大块 html,扫描它的<img>
标签,如果标签没有宽度 + 高度值,则应用它list($width, $height, $type, $attr);
?
更详细地说,我有一个 php 页面,其中包含另一个仅包含 html 的页面。我希望在输出到浏览器之前更改 html。
这是我正在查看的简化版本:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="content">
<?php
include_once("client-contributed-text-and-images.php");
?>
</div>
</body>
</html>
在下面的一些输入之后,我想出了以下内容:
<!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>
问题是它在中间生成了一个完整的html4文件,而只更改了第一个img标签,之后貌似没有输出代码:
<!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>
所以我换档并尝试 fopen() 并让它部分工作:
<!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>
这给了:
<!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>
现在我只需要一些帮助来弄清楚如何实现list($width, $height, $type, $attr);
包含正确的高度和高度(显然只有在它尚未设置时)。