Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...