Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

html - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...