这可能是一个时髦的问题,但我想知道是否有人可以想出一种方式如何把一大块html,扫描它的<img>
标签,如果标签没有宽度+身高值适用于list($width, $height, $type, $attr);
?通过PHP扫描并编辑img宽度高度输出前
更详细地说,我有一个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);
包括正确的和高度(显然只有当它尚未设置)。
所以这样的事情? '<?php $ doc = new DOMDocument(); $ doc-> loadHTMLFile(“filename.html”); /*在这里改变img标签莫名其妙...... */ echo $ doc-> saveHTML(); ?>' – Paul 2013-03-19 19:34:20
@Paul,确实如此。 – Brad 2013-03-19 19:46:23
这是/ *更改img标签在这里莫名其妙...... * /部分我不确定如何去坚持新的代码:) – Paul 2013-03-19 19:58:15