Question

I see this is possible using jQuery, but how can it be done in QueryPath?

Selecting HTML Comments with jQuery

If not, can anyone suggest an HTML parser that can select comments?

Était-ce utile?

La solution

QueryPath comes with an extension called QPXML that has several add-on methods. One of these is comment().

To use it, simply include it in your script:

include 'QueryPath/QueryPath.php';
include 'QueryPath/Extensions/QPXML.php';

htmlqp($html, $selector)->comment();

This will retrieve the first comment attached to the presently selected node(s).

If you have a really sophisticated set of comments all within the same nodes, you can do something like this:

$nodes = $qp->get();
foreach ($nodes as $node) {
   foreach ($node->childNodes as $child) {
      if ($child->nodeType == XML_COMMENT_NODE) {
         // $child is a comment.
         print $child->textContent;
      }
   }
}

This is a little uglier, but it gives better access to cases where one element has a lot of comments in it.

Autres conseils

To get ALL comments of HTML page via querypath :

    function  getAllComments($node) {
        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $child) {
                $this->getAllComments($child);
                if ($child->nodeType == XML_COMMENT_NODE) {
                    echo  $child->textContent;
                }
            }

        }
    }

    $html = $qp->get() ;
    getAllComments($html[0]);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top