tags:

views:

416

answers:

5

I was curious as to whether or not there exists a jQuery-style interface/library for PHP for handling HTML/XML files -- specifically using jQuery style selectors.

I'd like to do things like this (all hypothetical):

foreach (j("div > p > a") as anchor) {
   // ...
}


print j("#some_id")->html();


print j("a")->eq(0)->attr("name");

These are just a few examples.

I did as much Googling as I could but couldn't find what I was looking for. Does anyone know if something along these lines exist, or is this something I'm going to have to make from scratch myself using domxml?

+1  A: 

simplexml perhaps? Its syntax is different from jquery, but it does make traversing XML really easy.

It will however not work for HTML that is not valid XML.

Anti Veeranna
+1  A: 

Have you looked into using PHP's DOMDocument class?

http://us2.php.net/manual/en/book.dom.php

Not sure if this is exactly what you're looking for, but it does allow for searching a document by various attributes, and other such DOM manipulation.

Johrn
+9  A: 

PHP Simple HTML DOM Parser uses jQuery-style selectors. Examples from the documentation:

Modifying HTML elements:

// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

Scraping Slashdot:

// Create DOM from URL
$html = file_get_html('http://slashdot.org/');

// Find all article blocks
foreach($html->find('div.article') as $article) {
    $item['title']     = $article->find('div.title', 0)->plaintext;
    $item['intro']    = $article->find('div.intro', 0)->plaintext;
    $item['details'] = $article->find('div.details', 0)->plaintext;
    $articles[] = $item;
}

print_r($articles);
karim79
+2  A: 

Doing some more hunting, I think I might've found precisely what I was looking for:

phpQuery - jQuery port to PHP

Thanks everyone for your answers, I will definitely keep them in mind for other uses.

theotherlight
If phpQuery answers your question you should tick this as the answer.
karim79
I already tried, I need to wait 2 days until I can accept my own answer apparently.
theotherlight
+2  A: 

http://fluentdom.org/ is another alternative.

Justin