2011-06-28 86 views
0

这里有一些代码,如何获得div[class=title]和最近的<p>内容?我只知道如何获得div[class=title]的foreach,但不知道如何获得p。谢谢。php简单的html DOM问题

<?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 />'; 
} 
?> 

我要像输出:

text1 
destriction1 
destriction2 
------------------------------ 
text2 
destriction3 
destriction4 
destriction5 
------------------------------ 
text3 
destriction6 
destriction7 
------------------------------ 

回答

3

你试过像div[class=title] p选择?

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

孩子()函数也应该工作(如下图所示)

,将让你在每个标题div的,<p>,虽然不是下面的段落。要做到这一点,请使用next_sibling() function。这样的事情:

$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

太好了,谢谢你的最佳教导。 –