user1375126
user1375126

Reputation: 99

get complete 'div' content using class name or id using php

i got a page source from a file using php and its output is similar to

<div class="basic">

 <div class="math">

  <div class="winner">

   <div class="under">

        <div class="checker">

         <strong>check</strong>

        </div>

   </div>

  </div>

 </div>

</div>

from this i need to got only a particular 'div' with whole div and contents inside like below when i give input as 'under'(class name) . anybody suggest me how to do this one using php

<div class="under">

      <div class="checker">

         <strong>check</strong>

      </div>

 </div>

Upvotes: 1

Views: 33169

Answers (3)

Amal
Amal

Reputation: 76636

Function to extract the contents from a specific div id from any webpage

The below function extracts the contents from the specified div and returns it. If no divs with the ID are found, it returns false.

function getHTMLByID($id, $html) {
    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    $node = $dom->getElementById($id);
    if ($node) {
        return $dom->saveXML($node);
    }
    return FALSE;
}

$id is the ID of the <div> whose content you're trying to extract, $html is your HTML markup.

Usage example:

$html = file_get_contents('http://www.mysql.com/');
echo getHTMLByID('tagline', $html);

Output:

The world's most popular open source database

Upvotes: 7

snuffn
snuffn

Reputation: 2122

Try this:

$html = <<<HTML
<div class="basic">
    <div class="math">
        <div class="winner">
            <div class="under">
                <div class="checker">
                    <strong>check</strong>
                </div>
            </div>
        </div>
    </div>
</div>;
HTML;

$dom = new DOMDocument();

$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$div = $xpath->query('//div[@class="under"]');

$div = $div->item(0);

echo $dom->saveXML($div);

This will output:

<div class="under">
    <div class="checker">
        <strong>check</strong>
    </div>
</div>

Upvotes: 17

pbappia12
pbappia12

Reputation: 1

I'm not sure what you asking but this might be it

preg_match_all("<div class='under'>(.*?)</div>", $htmlsource, $output);

$output should now contain the inner content of that div

Upvotes: -2

Related Questions