jQuery-like interface for PHP?
Solution 1
Doing some more hunting, I think I might've found precisely what I was looking for:
Thanks everyone for your answers, I will definitely keep them in mind for other uses.
Solution 2
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);
Solution 3
The question is old but what you need is Query Path.
Solution 4
Trust me you are looking for xPath. I am showing you an example
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
$dom = new DOMDocument;
libxml_use_internal_errors(TRUE);
$dom->loadHTMLFile('http://somewhereinblog.net');
libxml_clear_errors();
$xPath = new DOMXPath($dom);
$links = $xPath->query('//h1//a'); //This is xPath. Really nice and better than anything
foreach($links as $link) {
printf("<p><a href='%s'>%s</a></p>\n", $link->getAttribute('href'), $link->nodeValue);
}
?>
Solution 5
The best one I found is https://github.com/scotteh/php-dom-wrapper
It works very similarly as jQuery, and it is fast.
I tried many libraries from other answers, but I didn't manage to port the manipulations I was doing in jQuery easily. With this one it was a breeze. I guess it will become more popular soon...
theotherlight
Updated on January 06, 2020Comments
-
theotherlight over 4 years
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?