Search code examples
phpdomsimple-html-dom

Fetch content of all div with same class using PHP Simple HTML DOM Parser


I am new to HTML DOM parsing with PHP, there is one page which is having different content in its but having same 'class', when I am trying to fetch content I am able to get content of last div, Is it possible that somehow I could get all the content of divs having same class request you to please have a look over my code:

<?php
    include(__DIR__."/simple_html_dom.php");
    $html = file_get_html('http://campaignstudio.in/');
    echo $x = $html->find('h2[class="section-heading"]',1)->outertext; 
?>

Solution

  • In your example code, you have

    echo $x = $html->find('h2[class="section-heading"]',1)->outertext; 
    

    as you are calling find() with a second parameter of 1, this will only return the 1 element. If instead you find all of them - you can do whatever you need with them...

    $list = $html->find('h2[class="section-heading"]');
    foreach ( $list as $item ) {
        echo $item->outertext . PHP_EOL;
    }
    

    The full code I've just tested is...

    include(__DIR__."/simple_html_dom.php");
    $html = file_get_html('http://campaignstudio.in/');
    
    $list = $html->find('h2[class="section-heading"]');
    foreach ( $list as $item ) {
        echo $item->outertext . PHP_EOL;
    }
    

    which gives the output...

    <h2 class="section-heading text-white">We've got what you need!</h2>
    <h2 class="section-heading">At Your Service</h2>
    <h2 class="section-heading">Let's Get In Touch!</h2>