在图片标签中替换alt时出错?

时间:2011-12-16 07:09:27

标签: php

我有一个使用simple_dom_html的测试代码:

<?php
include 'simple_html_dom.php';
$content = '<img src="name1.jpg" alt="name"><img src="name2.jpg" alt="name2">';
$html = new simple_html_dom();
$html->load($content);
$array_alt = array();
foreach($html->find('img') as $element) {
    $element->src = "new src";
    $array_alt[] = $element->alt;
}
for($i=0; $i<count($array_alt); $i++) {
    $array_alt[$i] = "test" . $i;
}
echo $html;

输出:

$html= '<img src="new src" **alt="name"**><img src="newsrc" **alt="name2"**>';

当echo $ content,alt没有从名称“name1”,“name2”更改为“test1”,“test2”,如何修复它时出错?

2 个答案:

答案 0 :(得分:2)

将您的两个循环更改为:

//....
$i=0;
foreach($html->find('img') as $element) {
    $element->src = "new src";
    $element->alt = "test" . $i;
    $i++;
}
//....

答案 1 :(得分:0)

<?php
include 'simple_html_dom.php';

$content = '<img src="name1.jpg" alt="name"><img src="name2.jpg" alt="name2">';
$html = new simple_html_dom();
$html->load($content);

$i=0;
foreach($html->find('img') as $element) {
    $element->src = "new src";
    $element->alt = "test".$i;
    $i += 1;
}

echo $html;

?>