PHP DOMDocument And DOMXpath
我正在尝试使用DOMDocument / DOMXpath在HTML块中找到最后一个段落标签,但似乎无法弄清楚。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # 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(); |
工作代码:
1 2 3 4 5 6 7 8 9 10 11 | # 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']); |
使用此代替:
1 |