get HTML element by attribute value in php

后端 未结 3 422
小蘑菇
小蘑菇 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: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.

提交回复
热议问题