Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text nodes with Symfony DomCrawler

Tags:

dom

php

symfony

Is there any way to select the text nodes of a parent element using Symfony's DomCrawler?

In jQuery you could use the contents() methods and check for nodeType == 3

like image 628
Dave Avatar asked Mar 22 '23 12:03

Dave


1 Answers

As far as I can tell, the Symfony Crawler doesn't allow you to traverse text nodes. For what the Crawler is typically used for, going as deep as text nodes probably isn't too common.

However, the DOMNodes that the Crawler really stores the data of the document in do allow text node traversal.

For instance, if you want to loop over all the nodes (including text nodes) of a Crawler (assuming it is already filtered down to one result), you can do:

foreach ($crawler->getNode(0)->childNodes as $node) {
    if ($node->nodeName === '#text') {
        // you have a text node
    }
}

A few things to note:

  1. The call to getNode() actually returns a DOMNode (code completion in my IDE is telling me DOMElement, but DOMNode is a safer bet as it is the base class), so it pulls it out of the context of the Crawler; from here you need to use DOMNode properties and methods.

  2. The nodeName property of a DOMNode is the element's HTML tag name, but in the case of a text node, it appears to be set to #text. Alternatively, you could also use $node instanceof DOMText to detect a text node.

I know this question is older, but I was having trouble with this too and wanted to get an answer for this as it popped up pretty high in Google.

like image 102
jzimmerman2011 Avatar answered Apr 01 '23 10:04

jzimmerman2011