php
  • html
  • dom
  • 2013-12-11 35 views 1 likes 
    1

    我使用簡單的HTML DOM來提取用戶幻想足球隊。我想要做的是在下面的源代碼中獲得每個玩家的「ID」號碼。因此,例如在下面的「ID」的股利是121使用簡單的HTML DOM來提取ID

    <div id="ismGraphical1" class='ismPitchElement {"coptr": null, "played": 0, "pos": 1,   "can_sub": 1, "ep_this": 4.5, "event_points": 2, "id": 121, "sub": 0, "m": 1, "copnr": null, "is_captain": false, "team": 6, "is_vice_captain": false, "type": 1, "ep_next": 4.5} '> 
    

    下面的代碼返回整個DIV,但我想只得到了ID。我試過使用嵌套for循環,但它不工作。我認爲這與div內的數組有關。但不知道從哪裏開始。如果任何人都可以在右側直接指向我,我將不勝感激

    $html = new simple_html_dom($result); 
    foreach($html->find('div.ismPitchElement') as $pitchview) 
    echo $pitchview; 
    

    回答

    0

    無需外部庫。您可以使用DOMXPath,這些類是PHP核心的一部分:

    $result = <<<EOF 
    <div id="ismGraphical1" class='ismPitchElement {"coptr": null, "played": 0, "pos": 1,   "can_sub": 1, "ep_this": 4.5, "event_points": 2, "id": 121, "sub": 0, "m": 1, "copnr": null, "is_captain": false, "team": 6, "is_vice_captain": false, "type": 1, "ep_next": 4.5} '> 
    EOF; 
    
    $doc = new DOMDocument(); 
    $doc->loadHTML($result); 
    $selector = new DOMXPath($doc); 
    
    foreach($selector->query('//@class[starts-with(., "ismPitchElement")]') as $classattr) { 
        // remove the prefix using `ltrim()` 
        $json = json_decode(ltrim($classattr->nodeValue, "ismPitchElement")); 
        var_dump($json->id); 
    } 
    

    輸出:

    int(121) 
    
    +0

    對不起,我誤解了 – hek2mgl

    +0

    已經更新了答案。你可以用更少的代碼完成你所看到的。 – hek2mgl

    +0

    Thx ..沒問題:) – hek2mgl

    1

    如果您仍想使用simplehtmldom LIB那麼多去做。

    foreach ($html->find('[class^=ismPitchElement]') as $el) { 
         print json_decode(ltrim($el->{'class'}, "ismPitchElement"))->{'id'}; 
        } 
    
    相關問題