使用 php 使用类名或 id 获取完整的“div”内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12110519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:51:13  来源:igfitidea点击:

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

phphtml

提问by user1375126

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

我使用 php 从文件中获得了一个页面源,其输出类似于

<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

由此,当我将输入作为 'under'(class name) 输入时,我只需要一个特定的“div”,其中包含整个 div 和内容,如下所示。有人建议我如何使用 php 来做这件事

<div class="under">

      <div class="checker">

         <strong>check</strong>

      </div>

 </div>

回答by snuffn

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>

回答by Amal Murali

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

从任何网页的特定 div id 中提取内容的功能

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

下面的函数从指定的 div 中提取内容并返回它。如果未找到具有该 ID 的 div,则返回 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;
}

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

$id<div>您尝试提取其内容的 ID ,$html是您的 HTML 标记。

Usage example:

用法示例:

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

Output:

输出:

The world's most popular open source database

回答by pbappia12

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

$output 现在应该包含该 div 的内部内容