這可能是一個時髦的問題,但我想知道是否有人可以想出一種方式如何把一大塊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