2013-09-25 55 views
2

我正在使用Symfony2 DomCrawler爲特定節點進行加密。如何在Symfony2中保留子節點標籤DomCrawler

我有一個DOMDocument裏面有一些html。 我在做什麼basicaly是,我正在尋找具有特定類名稱的<p>標記。

比方說,我有這個網站在$ DOM對象:

<p class="one">class one</p> 
<p class="two">class two is the <b>good</b> class</p> 
<p class="tree">class tree</p> 
<p class="four">class four</p> 

然後我使用

$crawler = new Crawler($dom); 
$class  = 'two'; 
$paragraphs = $crawler->filterXPath('//p'); 

foreach($paragraphs as $paragraph) { 
     if ($paragraph->hasAttribute('class') === false) { 
      continue; 
     } 

     $class = $paragraph->getAttribute('class'); 

     if($class == $class_name){ 
      $node_value = $paragraph->nodeValue; 
     } 

的問題是,在這裏,我得到

class two is the good class 

我想獲得

class two is the <b>good</b> class 

如何在結果中保留那些<b></b>標記?

回答

2

這是因爲<b></b>是子節點,而->nodeValue只取其內容。
你需要獲取子節點的內容,如another question

此示例工作在你的情況

$dom = <<<'STR' 
<p class="one">class one</p> 
<p class="two">class two is the <b>good</b> class</p> 
<p class="tree">class tree</p> 
<p class="four">class four</p> 
STR; 

$crawler = new Crawler($dom); 
$class_name = 'two'; 
$paragraphs = $crawler->filterXPath('//p'); 

foreach ($paragraphs as $paragraph) { 
    if (false === $paragraph->hasAttribute('class')) { 
     continue; 
    } 

    $class = $paragraph->getAttribute('class'); 

    if ($class == $class_name) { 
     $value = ''; 

     foreach ($paragraph->childNodes as $child) { 
      $value .= $paragraph->ownerDocument->saveHTML($child); 
     } 
    } 
} 

echo $value; // class two is the <b>good</b> class 
+0

優秀提到,非常感謝你 –