PHP DOMDocument和DOMXpath

时间:2011-06-01 20:24:11

标签: php domdocument domxpath

我正在尝试使用DOMDocument / DOMXpath在HTML块中找到最后一个段落标记,但似乎无法弄明白。

# 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 ( ) ...有关如何使用DOMDocument / 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']);

1 个答案:

答案 0 :(得分:2)

请改用:

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