How to get all the contents with foreach loop except for those having some class in simple html dom.php

Viewed 183

Suppose i have a code like this:

 <div class="container">
        <span class="toshow">item1</span>
        <span class="toshow">item2</span>
        <span class="toshow">item3</span>
        <span class="show">item4</span>
        <span class="notshow">item4</span>
        <span class="notshow">item5</span>
        <span class="another">item5</span>
        <span class="another">item5</span>
    </div>

Now i just want to show the items having class "toshow" excluding the "notshow" items:

<?php
foreach($html->find('div[class="container"]') as $element)
echo $elemtnt->plaintext.'<br>';
?>

Also, i have tried this to exclude the span having class "notshow" :

<?php
foreach($html->find('div[class="container"] span[class! = "notshow"]') as $element)
echo $elemtnt->plaintext.'<br>';
?>

How to show all items using foreach loop? simple_html_dom.php

2 Answers

if you use DOMXpath you can do something like:

    $xdoc = new DomDocument;
$xdoc->loadHTMLFile("xxxx");
$xpath = new DOMXpath($xdoc);
$xpath->query(".//*[contains(@class,'toshow')]");

or for notshow

$xpath->query(".//*[not(contains(@class,'notshow'))]");

To find all spans with class "toshow" you could use div[class="container"] span[class="toshow"]

For example

foreach($html->find('div[class="container"] span[class=toshow]') as $element) {
    echo $element->plaintext . PHP_EOL;
}

Output

item1
item2
item3

Or show all spans where the class not is notshow

foreach($html->find('div[class="container"] span[class!=notshow]') as $element) {
    echo $element->plaintext . PHP_EOL;
}

Output

item1
item2
item3
item4
item5
item5
Related