2

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']);
hakre
  • 193,403
  • 52
  • 435
  • 836
dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

2

Use this instead:

 print_r($node->parentNode->lastChild->nodeValue);
rahim asgari
  • 12,197
  • 10
  • 43
  • 53
  • Thanks for the comment! I got it to work! My working code is above. I will accept your answer thought cause it got me on the right path – dennismonsewicz Jun 01 '11 at 20:56