get HTML element by attribute value in php

后端 未结 3 418
小蘑菇
小蘑菇 2021-02-04 12:41

I need to extract some data from a webpage with php. The part that I\'m interested in is structured similarly to this:



        
相关标签:
3条回答
  • 2021-02-04 13:07

    Make two array

    $fruits=array();
    $animals=array();
    

    t and in loop when you get .

    if(target=='fruit') {
       array_push($fruits,$valueofelement);
    
    } else if ($target=='animal') {
       array_push($animals,$valueofelement);
    }
    
    0 讨论(0)
  • 2021-02-04 13:09

    use DOMXPath and queries:

    $doc = new DOMDocument();
    $doc->Load('yourFile.html');
    
    $xpath = new DOMXPath($doc);
    
    $fruits = $xpath->query("//a[@target='fruit']");
    foreach($fruits as $fruit) {
        // ...
    }
    
    $animals = $xpath->query("//a[@target='animal']");
    foreach($animals as $animal) {
        // ...
    }
    

    See this demo.

    0 讨论(0)
  • 2021-02-04 13:13

    Just continue on target attributes which aren't fruit, and then add the textContent of the elements to an array.

    $nodes = array();
    
    for ($i; $i < $a->length; $i++) {
        $attr = $a->item($i)->getAttribute('target');
    
        if ($attr != 'fruit') {
            continue;
        }
    
        $nodes[] = $a->item($i)->textContent;
    }
    

    $nodes now contains all the nodes of the elements which have their target attribute set to fruit.

    0 讨论(0)
提交回复
热议问题