1

3回ループするforループがあり、ループ内でshell_exec()実行され、バイナリが呼び出され、phantomjsその出力が返されます。この出力はその後、simplehtmldom に渡されますstr_get_html()

問題:str_get_html($html)が for ループに関与し、$htmlWeb ページの HTML で構成されている場合、2 番目または 3 番目のループではなく、最初のループのみが実行されます。ただし、単純な<a>タグ forを使用する$htmlと、for ループが完全に繰り返されます。

ここで何が起こっていますか、どうすれば解決できますか?

以下の 2 つの関数 (動作する関数と 1 回だけループする関数) の違いは、一方の行がコメント アウトされ、もう一方の行がコメント アウトされていることです。

親関数 (forここでのループは完全には繰り返されません)

public function action_asos() {


    // Site details
    $base_url = "http://www.mysite.com";

    // Category details
    $category_id = 7616;
    $per_page = 500;

    // Find number of pages in category
    $num_pages = 2;

    //THIS IS THE LOOP THAT CANNOT LOOP COMPLETELY!
    // Extract Product URLs from Category page
    for($i = 0; $i <= $num_pages; $i++) {
        echo "<h2>Page $i</h2>";
        $page = $i;
        $category_url = 'http://www.mysite.com/pgecategory.aspx?cid='.$category_id.'&parentID=-1&pge='.$page.'&pgeSize='.$per_page.'&sort=1';
        $this->extract_product_urls($category_url, $base_url);
    }
        echo "Yes.";
        flush();

}

PHP コード (親関数のループを 1 回だけループさせる)

public function extract_product_urls($category_url, $base_url) {


    set_time_limit(300);
    include_once('/home/mysite/public_html/application/libraries/simple_html_dom.php');

    // Retrieve page HTML using PhantomJS
    $html = $this->get_html($category_url);

    // Extract links
    $html = str_get_html($html);
    //$html = str_get_html('<a class="productImageLink" href="asdasd"></a>');
    foreach($html->find('.productImageLink') as $match) {
        $product_url = $base_url . $match->href;
        $product_url = substr($product_url, 0, strpos($product_url, '&'));  // remove metadata in URL string
        $this->product_urls[] = $product_url;
    }

    echo "done.";
    flush();

}

ヘルパー関数

/**
 * Gets the webpage's HTML (after AJAX contented has loaded, using PhantonJS)
 * @return [type] [description]
 */
public function get_html($url) {

    $url = escapeshellarg($url);    // prevent truncating after characters like `&`
    $script = path('base')."application/phantomjs/httpget.js";
    $output = shell_exec("phantomjs $script $url");

    return $output;

}
4

1 に答える 1

1

これを試して:

while($match = $html->find('.productImageLink')) {
    if (!is_object($match)) {
        break;
    } 
    . 
    . 
    .  
}
于 2012-08-21T16:20:46.190 に答える