开发者

php simple html dom question [closed]

开发者 https://www.devze.com 2023-03-16 09:28 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
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

精彩评论

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

关注公众号