2011-12-16 23 views
0

我使用有一个测试代码simple_dom_html:在图像标签中替换alt时出错?

<?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; 

OUTPUT:

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

错误时,回声$内容,ALT不名 “NAME1”, “NAME2” 到 “测试1” 改“ test2“,如何解决它?

+0

你得到什么错误? – xdazz 2011-12-16 07:12:07

回答

2

更改你的两个循环到:

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

?> 
相关问题