2011-06-28 12 views
0

div[class=title]<p>のコンテンツを取得する方法はいくつかあります。私はforeachでdiv[class=title]を取得する方法を知っていますが、どうすれば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のようなセレクタを試みたことがありますか?次の段落ではないが、あなたに各タイトルのdivで<p>を取得します子供()関数も動作するはずです

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

(下図参照)

。これを行うには、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

すばらしい、教えてくれてありがとう。 –