2011-06-01 59 views
2

我想使用DOMDocument/DOMXpath在HTML块中找到最后一段标记,但似乎无法弄清楚。PHP DOMDocument和DOMXpath

# Create DOMDocument Object 
     $dom = new DOMDocument; 
     # Load HTML into DomDocument Object 
     $dom->loadHTML($data['component2']); 

     # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness 
     $xpath = new DOMXPath($dom); 

     # Loop through each comment node 
     foreach($xpath->query('//p') as $node) { 
      // krumo($node->parentNode); 
      print_r($node->parentNode->lastChild); 
     } 
     exit(); 

print_r返回空DOMText Object () ...如何找到在使用DOM文档/ DOMXPath HTML块的最后一段什么想法?

工作代码:

# Create DOMDocument Object 
     $dom = new DOMDocument; 
     $dom->preserveWhiteSpace = false; 
     # Load HTML into DomDocument Object 
     $dom->loadHTML($data['component2']); 

     # Creat DOMXPath Object and load DOMDocument Object into XPath for magical goodness 
     $xpath = new DOMXPath($dom); 
     $q = $xpath->query('//div[@class="t_content"]/p[last()]'); 

     $data['component2'] = str_replace(utf8_decode($q->item(0)->nodeValue), "", $data['component2']); 

回答

2

使用这个代替:

print_r($node->parentNode->lastChild->nodeValue); 
+0

感谢您的评论!我得到它的工作!我的工作代码在上面。我会接受你的回答,因为它让我走上了正确的道路 – dennismonsewicz 2011-06-01 20:56:53