PHP Simple HTML DOM Parser: Select only DIVs with multiple classes

百般思念 提交于 2019-11-30 13:05:14

EDIT2: As this is a bug in the dom parser (tested on version 1.5), there is no simple way of doing this. Solution I could think of:

$find = $html->find(".class1");
$ret = array();
foreach ($find as $element) {
    if (strpos($element->class, 'class3') !== false) {
        $ret[] = $element;
    }
}
$find = $ret;

basically you find all the elements with class one than iterate through those elements to find the ones that have class two (in this case three).


Previous answer:

Simple answer (should work according to html spec):

find(".class1.class2")

this will look for any type of element (div,img,a etc..) that has both class1 and class2. If you want to specify the type of element to match add it to the beginning without a . like:

find("div.class1.class2")

If you have a space between the two specified classes it will match elements with both the classes or elements nested in the element with the first class:

find(".class1 .class2")

will match

<div class="class1">
  <div class="class2">this will be returned</div>
</div>

or

<div class="class1 class2">this will be returned</div>

edit: I tried your code and found that the solutions above do not work. The solution that does work however is as follows:

$html->find("div[class=class1 class2]")

You can also try this :

test.html

<h1 class="first second last">
    <p>Paragraph</p>
</h1>

Solution :

include "simple_html_dom.php";

$html = file_get_html('test.html');
$h1 = $html->find('h1');
foreach ($h1 as $h1) {
    $h1Class = ($h1->class);
    if($h1Class == 'first second last'){
        $item['test'] = 'success';
    }else{
        $item['test'] = 'fail';
    }
    $ar[] = $item;
}
echo "<pre>";
print_r($ar);

$html->find(div[class=classname1], div[class=classname2]);

or

$html->find(div.classname1, div.classname2);

I had thought simple html dom let you do:

$html->find(".class1.class2")

But I guess not. You can switch to this library if you want that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!