2012-08-13 71 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