简体   繁体   English

使用Symfony DomCrawler选择文本节点

[英]Select text nodes with Symfony DomCrawler

Is there any way to select the text nodes of a parent element using Symfony's DomCrawler? 有没有办法使用Symfony的DomCrawler选择父元素的文本节点?

In jQuery you could use the contents() methods and check for nodeType == 3 在jQuery中,您可以使用contents()方法并检查nodeType == 3

As far as I can tell, the Symfony Crawler doesn't allow you to traverse text nodes. 据我所知,Symfony Crawler不允许您遍历文本节点。 For what the Crawler is typically used for, going as deep as text nodes probably isn't too common. 对于Crawler通常使用的内容,与文本节点一样深入可能并不常见。

However, the DOMNodes that the Crawler really stores the data of the document in do allow text node traversal. 但是,Crawler真正存储文档数据的DOMNode确实允许文本节点遍历。

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: 例如,如果要循环遍历Crawler的所有节点(包括文本节点)(假设它已经过滤到一个结果),您可以执行以下操作:

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; getNode()的调用实际上返回了一个DOMNode(我的IDE中的代码完成告诉我DOMElement,但DOMNode是一个更安全的赌注,因为它是基类),所以它将它从Crawler的上下文中拉出来; from here you need to use DOMNode properties and methods. 从这里你需要使用DOMNode属性和方法。

  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 . DOMNode的nodeName属性是元素的HTML标记名称,但在文本节点的情况下,它似乎设置为#text Alternatively, you could also use $node instanceof DOMText to detect a text node. 或者,您也可以使用$node instanceof DOMText来检测文本节点。

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. 我知道这个问题比较老,但我也遇到了这个问题,并希望得到一个答案,因为它在谷歌中出现了很高的水平。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM