PHPHtmlParser\Dom\HtmlNode::text PHP Method

text() public method

Gets the text of this node (if there is any text). Or get all the text in this node, including children.
public text ( boolean $lookInChildren = false ) : string
$lookInChildren boolean
return string
    public function text($lookInChildren = false)
    {
        if ($lookInChildren) {
            if (!is_null($this->textWithChildren)) {
                // we already know the results.
                return $this->textWithChildren;
            }
        } elseif (!is_null($this->text)) {
            // we already know the results.
            return $this->text;
        }
        // find out if this node has any text children
        $text = '';
        foreach ($this->children as $child) {
            /** @var AbstractNode $node */
            $node = $child['node'];
            if ($node instanceof TextNode) {
                $text .= $child['node']->text;
            } elseif ($lookInChildren && $node instanceof HtmlNode) {
                $text .= $node->text($lookInChildren);
            }
        }
        // remember our result
        if ($lookInChildren) {
            $this->textWithChildren = $text;
        } else {
            $this->text = $text;
        }
        return $text;
    }

Usage Example

 public function testTextLookInChildrenAndNoChildren()
 {
     $p = new HtmlNode('p');
     $a = new HtmlNode('a');
     $a->addChild(new TextNode('click me'));
     $p->addChild(new TextNode('Please '));
     $p->addChild($a);
     $p->addChild(new TextNode('!'));
     $p->text;
     $p->text(true);
     $this->assertEquals('Please click me!', $p->text(true));
 }