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?
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);