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

后端 未结 3 1489
臣服心动
臣服心动 2020-12-18 16:21

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

相关标签:
3条回答
  • 2020-12-18 16:35

    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>
    
    0 讨论(0)
  • 2020-12-18 16:35

    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

    0 讨论(0)
  • 2020-12-18 16:51

    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
    
    0 讨论(0)
提交回复
热议问题