使用dom获取getattribute和tag值

时间:2014-04-29 07:46:13

标签: php dom

有类似的线程可用。我看着他们,并试图得到。在这里,我可以获得地址值,但phone数字和image url未来。

我在哪里弄错了?

function getData($url){
        $containers1 = $html->find('div.mapbox div.mapbox-text strong.street-address address');   
    foreach($containers1 as $container)
    {
        $comments = $container->find('span');
        $item = new stdClass();
        foreach($comments as $comment)
        {
            $address.= $comment->plaintext; //append the content of each span
        }
        echo $address; // this gives correct result
    }
    $containers2 = $html->find('div.mapbox div.mapbox-text span.biz-phone');
    $phone = $containers2->innertext;
        echo "<br/>".$phone."<br/>"; // no result
    $Imgcontainers = $html->find('div.js-photo photo photo-1 div.showcase-photo-box img');
        echo $Imgcontainers->getAttribute('src'); // Fatal error: Call to a member function getAttribute() on a non-object
}   
    }
    $url = 'http://www.yelp.com/biz/locanda-san-francisco?start=40';
    $root = getData($url);

更新

我补充说:

    $Imgcontainers = $html->find('div.photo-1 img');
    foreach($Imgcontainers as $cont){               
        $img[] = $cont->getAttribute('src');            
    }
    echo $img[0];

http://s3-media3.ak.yelpcdn.com/bphoto/Pf2RTD8pNdy-oUnp-57m4Q/ls.jpghttp://s3-media3.ak.yelpcdn.com/bphoto/Pf2RTD8pNdy-oUnp-57m4Q/ls.jpg

相同的网址两次?为什么我们只回显第0个数组值?

1 个答案:

答案 0 :(得分:1)

使用此代码

foreach($containers1 as $container)
{
  $comments = $container->find('span');
  $item = new stdClass();
  foreach($comments as $comment)
  {
        $address.= $comment->plaintext; //append the content of each span
  }
  echo $address; // this gives correct result
}
$containers2 = $html->find('div.mapbox div.mapbox-text span.biz-phone');
foreach($containers2 as $contact){
    $phone = $contact->plaintext;
}   
echo "<br/>".$phone."<br/>"; // no result
$Imgcontainers = $html->find('div.photo-1 img');
foreach($Imgcontainers as $cont){
    echo $cont->getAttribute('src');
}