2012-08-13 72 views
0

我所試圖做的是刮的旅行顧問頁 - 我有什麼,我從第一頁需要,然後我做另一個循環來從下一頁的內容,但當我嘗試將這些細節添加到現有數組中時,出於某種原因它不起作用。PHP簡單的HTML DOM解析器 - 結合兩種陣列

error_reporting(E_ALL); 
include_once('simple_html_dom.php'); 

$html = file_get_html('http://www.tripadvisor.co.uk/Hotels-g186534-c2-Glasgow_Scotland-Hotels.html'); 

$articles = ''; 

// Find all article blocks 
foreach($html->find('.listing') as $hotel) { 
    $item['name']  = $hotel->find('.property_title', 0)->plaintext; 
    $item['link']  = $hotel->find('.property_title', 0)->href; 

    $item['rating'] = $hotel->find('.sprite-ratings', 0)->alt; 
    $item['rating'] = explode(' ', $item['rating']); 
    $item['rating'] = $item['rating'][0]; 

    $articles[] = $item; 
} 

foreach($articles as $article) { 

    echo '<pre>'; 
    print_r($article); 
    echo '</pre>'; 

    $hotel_html = file_get_html('http://www.tripadvisor.co.uk'.$article['link'].'/'); 

    foreach($hotel_html->find('#MAIN') as $hotel_page) { 
     $article['address']   = $hotel_page->find('.street-address', 0)->plaintext; 
     $article['extendedaddress'] = $hotel_page->find('.extended-address', 0)->plaintext; 
     $article['locality']   = $hotel_page->find('.locality', 0)->plaintext; 
     $article['country']   = $hotel_page->find('.country-name', 0)->plaintext; 

     echo '<pre>'; 
     print_r($article); 
     echo '</pre>'; 

     $articles[] = $article; 
    } 
} 

echo '<pre>'; 
print_r($articles); 
echo '</pre>'; 

這裏是所有的調試輸出,我得到:http://pastebin.com/J0V9WbyE

網址:http://www.4playtheband.co.uk/scraper/

+0

*更好*使用SimpleXML的或的DomDocument。只是說。我知道這可能聽起來很蹩腳,因爲你不要求那樣做。所以我現在很沉默。 – hakre 2012-08-13 21:02:09

+0

使用的Web刮的XML庫的問題是,這將是無法容忍這是無效的XML,這很可能是即使網站自稱是XHTML任何標記的。 simple_html_dom以類似瀏覽器的「標籤湯」的方式進行解析,因此可以製作出更強大的刮板。 – IMSoP 2012-08-20 14:54:15

回答

1

我會改變

$articles = ''; 

到:

$articles = array(); 

之前的foreach():

$articlesNew = array(); 

當陣列上進行迭代,插入新的陣列

$articlesNew[] = $article; 

在最後在合併數組

$articles = array_merge($articles, $articlesNew); 

來源:http://php.net/manual/en/function.array-merge.php更多陣列PHP合併/合併。

我從來沒有試圖改變時,通過在PHP已經遍歷數組,但如果你這樣做與C++集合不當就會崩潰,除非你對致命的異常。我瘋狂的猜測是,你不應該在迭代它的時候改變數組。我知道我永遠不會那樣做。與其他變量一起工作。

+0

謝謝,我會試一試:) – martincarlin87 2012-08-20 14:57:36