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
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With