开发者

php simple html dom question [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Here are some codes, how to get the div[class=title] and the nearest <p> content? I only know how to get the div[class=title] in a foreach, but no idea how to get the p. Thanks.

<?php
header("Content-type: text/html; charset=utf-8");
require_once("simple_html_dom.php");
?>
<?php
$str = <<<ETO
<div id="content">
<div class="title"><p>text1</p></div>
<p>destriction1</p>
<p>destriction2</p>
<div class="title"><p>text2</p></div>
<p>destriction3</p>
<p>destriction4</p>
<p>destriction5</p>
<div class="title"><p>text3</p></div>
<p>destriction6</p>
<p>destriction7</p>
</div>
ETO;
$html = str_get_html($str);
foreach($html->find("div[class=title]") as $content){
    echo $content.'<hr />';
}
?>

I want output like:

text1
destriction1
destriction2
------------------------------
text2
destriction3
destriction4
destrictio开发者_运维百科n5
------------------------------
text3
destriction6
destriction7
------------------------------


Have you tried a selector like div[class=title] p?

$html = str_get_html($str);
foreach($html->find("div[class=title] p") as $content){
    echo $content.'<hr />';
}

The children() function should also work (shown below)

That will get you the <p> in each title div, although not the following paragraphs. To do that, use the next_sibling() function. Something like this:

$html = str_get_html($str);
foreach($html->find("div[class=title]") as $content){
    // $content = <div class="title">.  first_child() should be the <p>
    echo $content->first_child().'<hr />';

    // Get the <p>'s following the <div class="title">
    $next = $content->next_sibling();
    while ($next->tag == 'p') {
        echo $next.'<hr />';
        $next = $next->next_sibling();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜