Get data-filter attribute of all divs

时间:2017-08-04 12:53:19

标签: php html

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.

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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');
}

答案 2 :(得分:0)

以下代码对我有用:

   $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>';
   }

有关此问题的详情,请参阅DOMDocument::loadHTMLFile in the PHP documentation