garretus / phpquery

Automatically exported from code.google.com/p/phpquery
0 stars 0 forks source link

Select only text nodes #183

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
I tried recreating the following jQuery code which returns only the child text 
nodes of the selected element in phpQuery but with no luck.

jQuery:
$(elem).contents().filter(function() { return this.nodeType == 3; });

phpQuery:
<p>
The text node that I want
<span>The one I don't want</span>
Another text node that I want
</p>

pq($elem)->contents()->filter(new Callback('filterTextNode'));

function filterTextNode($index, $node) {
    return $node->nodeType == 3;
}

The nodeType variable is always set to 1. How can I get this to work?

Original issue reported on code.google.com by patrick....@gmail.com on 5 May 2011 at 8:34

GoogleCodeExporter commented 8 years ago
$response = "<p>
The text node that I want
<span>The one I don't want</span>
Another text node that I want
</p>
";

$docHTML = phpQuery::newDocument($response);
phpQuery::selectDocument($docHTML);

$result = pq('p')->contents();
foreach($result as $node){  

    if($node->nodeType === 3) {
        //remove empty lines
        $textNode = trim($node->nodeValue);

        if($textNode){
        // display text in browser
        echo "</br>" . $node->nodeValue ." </br>";
        }
    }   
}

Original comment by moyar...@gmail.com on 17 Sep 2013 at 5:12

GoogleCodeExporter commented 8 years ago
this is the way to do this function but using your code (with filtering)

$response = "<p>
The text node that I want
<span>The one I don't want</span>
Another text node that I want
</p>
";

$docHTML = phpQuery::newDocument($response);
phpQuery::selectDocument($docHTML);

$result  = pq('p')->contents()->filter(new Callback('filterTextNode'));

function filterTextNode($index, $node) {
    return $node->nodeType === 3;
}

//display all the nodes in the browser
echo "</br>" . $result ." </br>";

//Loop through the nodes
foreach($result as $node){  

        //remove empty lines
        $textNode = trim($node->nodeValue);

        if($textNode){
        // display text in browser
        echo "</br>" . $node->nodeValue ." </br>";
        }
}

Original comment by moyar...@gmail.com on 17 Sep 2013 at 5:20