Menu

#22 How to find multiple attributes

v1.0_(example)
closed
None
1
2019-04-20
2013-05-02
Alon
No

Hi,
I've just started using the parser and I need to parse an HTML page and get 'tr' tags with class 'even' that don't have an 'id' attribute. I tried a couple of approaches like:
$html->find('tr.even[!id]');
or
$html->find('tr[!id].even');

but none seems to work.
Is it possible to search for multiple attributes?

thanks,
Alon.

Discussion

  • pixeline

    pixeline - 2013-12-08

    I would select all tr.even then in the foreach, bypass those that do have the "id" attribute

    $ret = $html->find('div[id]'); foreach($html->find('tr[class=even]') as $e) if(!$e->id){ // process the data... } }

     

    Last edit: pixeline 2013-12-08
  • John Schlick

    John Schlick - 2013-12-09

    Remember that find returns an array of dom objects (this is implicit in the answer pixeline gave).

     
  • LogMANOriginal

    LogMANOriginal - 2019-04-20
    • status: open --> closed
    • assigned_to: LogMANOriginal
    • discussion: enabled --> disabled
     
  • LogMANOriginal

    LogMANOriginal - 2019-04-20

    Closing because this works in the latest version.
    You can do it exactly in the way you wanted to do it initially
    $html->find('tr.even[!id]');
    or use the alternative version
    $html->find('tr[class*="even"][!id]');

    Here is my test script for reference.

    <?php
    
    require_once 'simple_html_dom.php';
    
    $html = str_get_html(
    <<<EOD
    <html>
    <body>
        <table>
            <tr class="odd"><td>row 1</td></tr>
            <tr class="even" id="summary"><td>row 2 (summary)</td></tr>
            <tr class="odd"><td>row 3</td></tr>
            <tr class="even"><td>row 4</td></tr>
            <tr class="odd"><td>row 5</td></tr>
            <tr class="even" id="special"><td>row 6 (special)</td></tr>
            <tr class="odd"><td>row 7</td></tr>
            <tr class="even"><td>row 8</td></tr>
        </table>
    </body>
    </html>
    EOD
    );
    
    foreach($html->find('tr.even[!id]') as $tr) {
        echo $tr->plaintext . PHP_EOL;
    }
    
    echo '--- alternative ---' . PHP_EOL;
    
    foreach($html->find('tr[class*="even"][!id]') as $tr) {
        echo $tr->plaintext . PHP_EOL;
    }
    
    /**
     * Expected:
     *
     * row 4
     * row 8
     */
    
     
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.