0

我想要做的是在 Trip Advisor 上抓取一个页面 - 我从第一页获得了我需要的内容,然后我执行另一个循环以从下一页获取内容但是当我尝试将这些详细信息添加到现有数组时由于某种原因不起作用。

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/

4

1 回答 1

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++ 集合执行此操作,除非您处理致命异常,否则它将崩溃。我的疯狂猜测是您不应该在迭代时更改数组。我知道我永远不会那样做。使用另一个变量。

于 2012-08-20T14:48:11.673 回答