2014-04-29 77 views
0

也有類似的線程可用。我看着他們,試圖得到。在這裏我可以得到地址值,但phone號碼和image url不在。使用dom獲取屬性和標記值

我在哪裏犯錯?

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

UPDATE

我加了這一點:

$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

相同的URL兩次?爲什麼兩次,雖然我們僅回顯第0個數組值?

+0

是否使用簡單的HTML DOM解析器? –

+1

只需使用一個獨特的類來讀取圖像標籤$ Imgcontainers = $ html-> find('div.photo-1 img'); – Manibharathi

回答

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'); 
} 
+0

謝謝親愛的,但它給 - - http://s3-media3.ak.yelpcdn.com/bphoto/Pf2RTD8pNdy-oUnp-57m4Q/ls.jpg//s3-media2.ak.yelpcdn.com/photo/qifZoydAoHDzenurxpsM0Q/ 30s.jpg'我把它改成'find('div.showcase-photo-box img'); '給出'http://s3-media3.ak.yelpcdn.com/bphoto/Pf2RTD8pNdy-oUnp-57m4Q/ls.jpghttp://s3-media3.ak.yelpcdn.com/bphoto/WWcu9lz65KLtOTsFZnIHPw/ls.jpghttp: //s3-media2.ak.yelpcdn.com/bphoto/NWYEgpRzMiAFrGvs_6aQAQ/ls.jpghttp://s3-media4.ak.yelpcdn.com/bphoto/hQKPu2XQ8YUUBvkZgfvXcA/180s.jpghttp://s3-media1.ak.yelpcdn。 com/bphoto/Njz41l4ku_uQLuwqiuLIu ...' – user123

+1

使用像'$ img [] = $ cont-> getAttribute('src')這樣的數組變量;'然後我們可以獲得數組中的所有圖像。 – Manibharathi

+0

請參閱我的更新問題 – user123