简体   繁体   中英

Get data-filter attribute of all divs

I have following html:

<div class="" data-filter="01">
    ...
</div>
<div class="" data-filter="02356">
    ....
</div>
<div class="" data-filter="02356">
    ...
</div>

How can I get the data-filter attribute of all those divs in PHP?

I've tried something like

$doc = new DOMDocument();
$doc->loadHTMLFile("items.html");

foreach ($doc->childNodes as $item){
    echo $item->getAttribute('data-filter');
}

but that throws Call to undefined method error .

Try this code:

$doc = DOMDocument::loadHTML($html);
$xpath = new DOMXPath($doc);
$query = "//div[@class='']";
$entries = $xpath->query($query);
foreach ($entries as $entry) {
    echo "Found: " . $entry->getAttribute("attrloc");
}

or use this php

http://simplehtmldom.sourceforge.net/manual.htm

change your code as below: need to cahnge method in foreach

$doc = new DOMDocument();
$doc->loadHTMLFile("items.html");

foreach ($doc->getElementsByTagName('div') as $item){    
  echo $item->getAttribute('data-filter');
}

The following code worked for me:

   $doc = new DOMDocument();
   $doc->loadHTMLFile("items.html");

   $elements = $doc->getElementsByTagName('div');

   if (!is_null($elements)) {
   foreach ($elements as $element) {
       echo $element->getAttribute('data-filter').'<br>';
   }

For more information regarding this, please see DOMDocument::loadHTMLFile in the PHP documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM