views:

99

answers:

4

Hi,

I'm wondering that if there's something like JQuery's $('element.selector') implemented for PHP?

When I CURL and I got HTML codes from the remote site, I'd like to select only the tags I want before I send out to my HTML.

Thanks

+13  A: 

The PHP Simple HTML DOM Parser has a similar functionality:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';
Gumbo
LOL I reversed my opinion when i noticed the download link to dom parser. Excuse me ;-) Thanks for showing me HTML DOM Parser even tho i handle nothing but XHTML these days and just use DOM.
hopeseekr
DOMDocument / DOMXPath is _extremely_ faster, implemented at C level, and it can equally deal with malformed HTML, maybe even better. Writing some helper functions altering 'jquery'/ 'css' selectors in XPath is not that hard.
Wrikken
+1  A: 
$ctx = xpath_new_context($doc); 
$xpath_nodes = xpath_eval($ctx, "//some_element"); 
botmonster
This is a great solution, but it assumes the developer has written compliant and well formed xml for their html output, which I've found is rarely the case unless there is strict enforcement of it within the development cycle (which again is rare).
Nick Shepherd
I used to run bad code through the tidy extension. Problem solved.
hopeseekr
+4  A: 

Or perhaps Querypath (http://querypath.org/)? Just read about it yesterday and it looks kind of cool.

A: 

You could use server-side javascript. Haven't done that myself yet, though.

Wouter Lievens