簡體   English   中英

Simplehtmldom獲取第一個元素

[英]Simplehtmldom get first element

當我解析一些html並獲取html元素數組時,我想獲取第一項。 這是代碼:

    $url  = getLink($good);
    $html = file_get_html($url);

    $offers = array_filter($html->find('div.b-offers'), function($node) {
        return $node->class == 'b-offers'; // If this only class is set
    });

    // $offer    = $offers[0];  // <---- look here
    foreach ($offers as $offer) {
        $price    = $offer->find('span.b-prices__num', 0)->innertext();
        break;
    }

僅當我立即使用foreach和break時,它才有效。 但是,為什么$ offer = $ offers [0]不起作用? 如果我這樣寫,這里將出現錯誤:

$price = $offer->find('span.b-prices__num', 0)->innertext();

就像在非對象上調用find()函數一樣。

另外一個問題是:在使用array_filter函數獲取只有一個“ b-offers”類的元素時,是否可以重寫代碼? 我記得我嘗試了一些不同的方法,例如

$html->find('div[class="b-offers"]')

或某種類型,但對我不起作用

$offer = $offers[0]; 不起作用,因為array_filter不會返回基於0索引的數組。 它保留了先前數組的鍵。

為什么$ offer = $ offers [0]不起作用? 我認為因為此時$offers仍然是一個對象而不是數組

要獲得只有一個類“ b-offers”的元素,請嘗試$html->find('div.b-offers');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM