Search code examples
phpdomdocumentdomxpath

PHP DOMDocument And DOMXpath


I am trying to find the last paragraph tag in a block of HTML using DOMDocument/DOMXpath but can't seem to figure it out.

# 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();

The print_r returns an empty DOMText Object ( )... any idea on how to find the last paragraph in a block of HTML using DOMDocument/DOMXPath?

Working Code:

# 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']);

Solution

  • Use this instead:

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