1

我需要打印出我的数组,但print_r($test)最终不起作用......

这是一个简单的代码:

$code = '<html><head></head><body><div class="list"><a href="http://google.com" title="my title"><img src="http://google.com/564308080517287.jpg" alt="my title"></a></div></body></html>'; // Code is simplified here, but imagine you've got much more contents inside
$doc = new DOMDocument();
$doc->loadHTML( $code );
//
$test = array();
foreach($doc->getElementsByTagName('div') as $div){
    if($div->getAttribute('class') == "list"){
        $ads_count = $div->getElementsByTagName('a')->length;
        for ($i=0; $i<=$ads_count; $i++) {
            $ad = $div->getElementsByTagName('a')->item($i);
            $ad_img = trim($ad->getElementsByTagName('img')->item(0)->getAttribute('src'));
            $test[$i]['img'] = $ad_img;
        }
    }
}
print_r($test); // doesn't work !!

任何的想法 ?

4

1 回答 1

1
  <?php
   $code = '<html><head></head><body><div class="list">
    <a href="http://google.com" title="my title"><img src="http://google.com/564308080517287.jpg" alt="my title"></a></div></body></html>'; // Code is simplified here, but imagine you've got much more contents inside
  $dom = new DOMDocument();
  $dom->loadHtml($code);
  $selector   = new DOMXPath($dom);
  $parceiltable    =   $selector->query("//div[@class='list']/a/img");

  foreach($parceiltable as $key=>$tds){
     $test[]['img']    =   $tds->getAttribute('src');
  }

  print_r($test); 
?>
于 2013-09-08T18:58:59.947 回答