PHP simple_html_dom回显顺序

时间:2014-03-22 11:37:17

标签: php html

我试着获取img的alt值及其href链接我创建了这个片段,但它是回显链接然后是alt值我怎样才能让它回显alt值然后链接?

html

 <div id="images"><div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div>
    <div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div>
    <div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div></div></div>

任何我的PHP code

$html = new simple_html_dom();  
$html = $html->load($page);
foreach($html->find('div[id=images],img[alt],a[class=url]') as $element) {
$g .="$element->alt\n  $element->href";
echo $g;
    }

为什么此代码无法生效$g .="$element->alt\n $element->href"; ?

2 个答案:

答案 0 :(得分:0)

你要迭代的东西是img的父级和a,它始终是.img-logo-big

foreach($html->find('.img-logo-big') as $img){
  echo $img->find('img', 0)->alt . "\n";
  echo $img->find('a', 0)->href . "\n";
}

答案 1 :(得分:-1)

因为您已经在变量$g

中获取了标记

这样做你将得到alt值和图像值与那些结果标签分开

$g='<div id="images"><div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div>
    <div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div>
    <div class="img-logo-big" style="width: 130px"><a class="url" href="http://link.com"><img src="http://host.com/images/image.jpg" alt="image name" /></a></div></div></div>';

preg_match_all('/<a class="url" href=(.*?)>|<img (?:.*?) alt=(.*?)\/>/', $g, $matches);
echo '<pre>';
print_r(array_values(array_filter($matches[1])));
print_r(array_values(array_filter($matches[2])));
相关问题