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?
All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag.
It is common to see jQuery programs call $(document) or $(this) , for example. jQuery objects can represent more than one element in a document, and you can also pass an array of elements to $() . In this case, the returned jQuery object represents the set of elements in your array.
jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With